Python Web抓取错误:使用split函数后,'NoneType'对象不可调用

问题描述 投票:0回答:2

我是一个初学者,正在编写我的第一个抓稿,试图从以下page中提取公司名称,电话号码和电子邮件。

到目前为止,我的脚本成功地取出了名称和电话号码,但我仍然不愿意拔出嵌套在脚本对象中的电子邮件。我最近的两次尝试涉及使用正则表达式,当失败时,一个拆分函数,它返回标题中提到的错误。

脚本:

import re
import requests

from urllib.request import urlopen
from bs4 import BeautifulSoup

url1 = "http://pcoc.officialbuyersguide.net/Listing?MDSID=CPC-1210"
html = urlopen(url1)
soup = BeautifulSoup(html,'html.parser')

for company_name in soup.find_all(class_='ListingPageNameAddress NONE'):
    print(company_name.find('h1').text)

for phone in soup.find_all(class_='ListingPageNameAddress NONE'):
    print(phone.find(class_='Disappear').text)

for email in soup.findAll(class_='ListingPageNameAddress NONE'):
    print(email.find('script').text)
    print(email.split('LinkValue: "')[1].split('"')[0])
    print(re.findall(r"([\w\._]+\@([\w_]+\\.)+[a-zA-Z]+)", soup))

错误:

TypeError                                 Traceback (most recent call last)
<ipython-input-20-ace5e5106ea7> in <module>
      1 for email in soup.findAll(class_='ListingPageNameAddress NONE'):
      2     print(email.find('script').text)
----> 3     print(email.split('LinkValue: "')[1].split('"')[0])
      4     print(re.findall(r"([\w\._]+\@([\w_]+\\.)+[a-zA-Z]+)", soup))

TypeError: 'NoneType' object is not callable

我试图从中提取的“脚本”中的HTML:

EMLink('com','aol','mikemhnam','<div class="emailgraphic"><img style="position: relative; top: 3px;" src="https://www.naylornetwork.com/EMailProtector/text-gif.aspx?sx=com&nx=mikemhnam&dx=aol&size=9&color=034af3&underline=yes" border=0></div>','pcoc.officialbuyersguide.net Inquiry','onClick=\'$.get("TrackLinkClick", { LinkType: "Email", LinkValue: "[email protected]", MDSID: "CPC-1210", AdListingID: "" });\'')

python web-scraping split nonetype
2个回答
0
投票

据我所知,BeautifulSoup不会在元素上公开split函数。

BeautifulSoup元素允许您指定任何属性,如果它不是元素的属性或函数,它将查找具有该名称的标记。例如,element.div将找到element的第一个后代,即div。所以你甚至可以做像element.nonsense这样的事情,因为nonsense不是element对象的函数或属性,它然后在文档树中搜索名为nonsense的后代,并且因为一个不存在,它将只返回None

因此,当您调用email.split(...)时,它在split对象上找不到名为email的函数或属性,因此它在HTML树中搜索名为split的标记。由于它找不到名为split的元素,它返回None,并且您尝试将其称为函数,这会导致您获得的错误。

您是否有可能从电子邮件email.text.split()获取文本?


0
投票

试试这个,这可能会解决你的问题。

import re
import requests

from urllib.request import urlopen
from bs4 import BeautifulSoup

url1 = "http://pcoc.officialbuyersguide.net/Listing?MDSID=CPC-1210"
html = urlopen(url1)
soup = BeautifulSoup(html,'html.parser')

for company_name in soup.find_all(class_='ListingPageNameAddress NONE'):
    print(company_name.find('h1').text)

for phone in soup.find_all(class_='ListingPageNameAddress NONE'):
    print(phone.find(class_='Disappear').text)

for email in soup.findAll(class_='ListingPageNameAddress NONE'):
    print(email.find('script').text)
    a=email.find('script').text
#    print(email.split('LinkValue: "')[1].split('"')[0])
    print(str(re.findall(r"\S+@\S+", a)).split('"')[1])
© www.soinside.com 2019 - 2024. All rights reserved.