使用beautifulSoup在元素中抓取数据

数量

我正在使用beautifulSoup 进行网页抓取。我设法抓取了名称,但是问题是,如果数据在元素中,例如电话号码和电子邮件位于如下图所示的位置,我真的不确定如何抓取:

电子邮件

电话

我的代码:

 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")

我的抓取结果是“点击电子邮件”和“点击电话”。我应该修复什么才能使结果是正确的电子邮件和电话号码?

stackoverflow用户

您必须从链接中获取数据属性的值。你可以试试这个代码 -

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")

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

使用[[]]从列表中抓取元素

如何使用beautifulsoup在h4中抓取数据?

如何使用BeautifulSoup从Python中基于数据自动属性的div类中抓取内容?

如何使用python或javascript在<canvas>元素中抓取数据?

使用beautifulsoup从脚本标签中抓取数据

使用BeautifulSoup抓取财务数据

使用BeautifulSoup按Python中的元素抓取HTML

在404中使用beautifulsoup结果抓取数据

使用 Python-BeautifulSoup 抓取表格数据

使用beautifulsoup python从页面中抓取特定元素时遇到问题

使用 BeautifulSoup 从数据框中抓取数据

使用 BeautifulSoup 从 html 中抓取特定数据

使用 BeautifulSoup 从网站抓取数据的问题

使用 beautifulsoup 在 Pandas 数据框中抓取问题/错误

使用 BeautifulSoup 从 wiki 类别中抓取数据

如何使用beautifulsoup从python中的url中抓取数据

使用 Python Beautifulsoup 抓取表格和数据

使用 BeautifulSoup 抓取数据

使用 BeautifulSoup 抓取 CSS 类中的特定元素

如何使用 BeautifulSoup 抓取特定数据

使用 BeautifulSoup 和 Selenium 的网页抓取网站不会检测网页中的表格元素

使用 BeautifulSoup 抓取 Web 数据

不使用beautifulsoup抓取网站数据

使用 BeautifulSoup 从 Zillow.com 抓取数据

使用 Requests 和 Beautifulsoup 抓取数据

使用 BeautifulSoup 抓取時如何處理某些頁面中缺失的元素

如何使用 Python 和 BeautifulSoup 从 html 表中抓取数据?

使用 Python 抓取 HTML 中的特定元素:BeautifulSoup4

使用 BeautifulSoup 和 Selenium 抓取数据