[英]Beautifulsoup can't find text
我正在尝试使用urllib和漂亮的汤在python中编写一个刮板。 我有一个csv URL,用于新闻报道,大约80%的页面都适用于该抓取工具,但当新闻顶部有图片时,脚本将不再花费时间或正文。 我大多感到困惑,因为汤.find和汤.find_all似乎不会产生不同的结果。 我尝试了各种不同的标记,这些标记应该捕获文本以及“ lxml”和“ html.parser”。
这是代码:
testcount = 0
titles1 = []
bodies1 = []
times1 = []
data = pd.read_csv('URLsALLjun27.csv', header=None)
for url in data[0]:
try:
html = urllib.request.urlopen(url).read()
soup = BeautifulSoup(html, "lxml")
titlemess = soup.find(id="title").get_text() #getting the title
titlestring = str(titlemess) #make it a string
title = titlestring.replace("\n", "").replace("\r","")
titles1.append(title)
bodymess = soup.find(class_="article").get_text() #get the body with markup
bodystring = str(bodymess) #make body a string
body = bodystring.replace("\n", "").replace("\u3000","") #scrub markup
bodies1.append(body) #add to list for export
timemess = soup.find('span',{"class":"time"}).get_text()
timestring = str(timemess)
time = timestring.replace("\n", "").replace("\r","").replace("年", "-").replace("月","-").replace("日", "")
times1.append(time)
testcount = testcount +1 #counter
print(testcount)
except Exception as e:
print(testcount, e)
这是我得到的一些结果(标有“ nonetype”的是成功提取标题但正文/时间为空的结果)
1 http://news.xinhuanet.com/politics/2016-06/27/c_1119122255.htm
2 http://news.xinhuanet.com/politics/2016-05/22/c_129004569.htm'NoneType '对象没有属性'get_text'
任何帮助将非常感激! 谢谢。
编辑:我没有'10信誉点',所以我不能发布更多链接进行测试,但是如果您需要更多页面示例,将会与他们发表评论。
问题是网站上没有带图片的class="article"
,也没有带有"class":"time"
。 因此,似乎您必须检测网站上是否有图片,然后如果有图片,请按以下方式搜索日期和文本:
对于日期,请尝试:
timemess = soup.find(id="pubtime").get_text()
对于正文,文章似乎只是图片的标题。 因此,您可以尝试以下操作:
bodymess = soup.find('img').findNext().get_text()
简而言之, soup.find('img')
找到图像, findNext()
转到下一个包含文本的块。
因此,在您的代码中,我将执行以下操作:
try:
bodymess = soup.find(class_="article").get_text()
except AttributeError:
bodymess = soup.find('img').findNext().get_text()
try:
timemess = soup.find('span',{"class":"time"}).get_text()
except AttributeError:
timemess = soup.find(id="pubtime").get_text()
作为Web抓取的一般流程,我通常使用浏览器访问网站本身,并首先在浏览器中找到网站后端中的元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.