[英]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.