我试图用python编写一个scraper,使用urllib和beautifulsoup。我有一个csv网址的新闻故事,和约80%的网页刮板工作,但当有一个图片在顶部的故事,脚本不再拉时间或正文文本。我很困惑因为汤。找以及汤。找到所有似乎不会产生不同的结果。我已经尝试了各种不同的标签,它们可以捕捉文本以及'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”的结果是标题被成功提取,但是body/time是空的)
1http://news.xinhuanet.com/politics/2016-06/27/c_1119122255.htm
2http://news.xinhuanet.com/politics/2016-05/22/c_129004569.htm“NoneType”对象没有属性“get_text”
任何帮助都将不胜感激!谢谢。在
编辑:我没有'10声誉点',所以我不能张贴更多的链接测试,但会与他们评论,如果你需要更多的网页例子。在
问题是网站上没有}相同的图片。因此,您似乎必须检测网站上是否有图片,然后如果有图片,请按如下方式搜索日期和文本:
class="article"
和{对于日期,请尝试:
对于正文,这篇文章似乎只是图片的标题。因此,您可以尝试以下操作:
^{pr2}$简而言之,
soup.find('img')
找到图像,findNext()
转到下一个包含文本的块。在因此,在您的代码中,我将执行以下操作:
作为网页抓取的一般流程,我通常使用浏览器去网站本身,先在浏览器中找到网站后端的元素。在
相关问题 更多 >
编程相关推荐