简体   繁体   English

使用beautifulSoup在元素中抓取数据

[英]Scraping data in element using beautifulSoup

I am doing web scraping using beautifulSoup.我正在使用beautifulSoup 进行网页抓取。 I managed to scrape the name, however the problem is, I don't really sure how to scrape if the data is in the elements for example the phone number and email are located as in the pictures below:我设法抓取了名称,但是问题是,如果数据在元素中,例如电话号码和电子邮件位于如下图所示的位置,我真的不确定如何抓取:

电子邮件

电话

My code:我的代码:

 import requests
    from bs4 import BeautifulSoup

    raw = requests.get('https://www.iproperty.com.my/property/findanagent.aspx?ty=as&ak=&rk=&pg=1&rmp=10&st=KL&ct=&st1=&ct1=#40091').text
    raw = raw.replace("</br>", "")

    soup = BeautifulSoup(raw, 'html.parser')

    import re

phone = ['data-content'])[0][1:][:-1] for d in soup.find_all('a',{'class':'csagentphonelead'})]
    name = [x.text.strip().split("\r\n")[-1].strip() for x in soup.find_all("p", class_='box-listing_agentCS')]
    website = [x.text.strip().split("\r\n")[-1].strip() for x in soup.find_all("a", class_='csagentemaillead')] 

    num_page_items = len(name)
    with open('results180.csv', 'a') as f:
        for i in range(num_page_items):
        f.write(name[i] + "," + phone[i] + "," + website[i] + "," + "\n")

My results from scraping is "Click for Email" and "Click for Phone".我的抓取结果是“点击电子邮件”和“点击电话”。 What should I fix so that the results are proper email and phone number?我应该修复什么才能使结果是正确的电子邮件和电话号码?

You have to get the value of data attribute from the link.您必须从链接中获取数据属性的值。 You can try this code -你可以试试这个代码 -

import requests
from bs4 import BeautifulSoup

raw = requests.get('https://www.iproperty.com.my/property/findanagent.aspx?ty=as&ak=&rk=&pg=1&rmp=10&st=KL&ct=&st1=&ct1=#40091').text
raw = raw.replace("</br>", "")

soup = BeautifulSoup(raw, 'html.parser')

import re
#['data-content'])[0][1:][:-1] ## note sure what is this
# for d in soup.find_all('a',{'class':'csagentphonelead'}):
name = [x.text.strip().split("\r\n")[-1].strip() for x in soup.find_all("p", class_='box-listing_agentCS')]
phone = [x['data'].strip().split("\r\n")[-1].strip() for x in soup.find_all("a", class_='csagentphonelead')] 
website = [x['data'].strip().split("\r\n")[-1].strip() for x in soup.find_all("a", class_='csagentemaillead')] 

num_page_items = len(name)
with open('results180.csv', 'a') as f:
    for i in range(num_page_items):
        f.write(name[i] + "," + phone[i] + "," + website[i] + "," + "\n")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM