我試圖通過 url 串列在 html 文本中查找某些內容并將其寫入新串列。我遇到的問題是,雖然我有一個 for 回圈,但它只輸出最后一個 url(串列“urls”中有 500 個)。我不知道如何讓它迭代寫入然后進入下一個迭代而不是迭代然后只寫串列中的最后一個。關于如何使其作業的任何想法?
for url in urls:
try:
page = urlopen(url)
except:
print("Error opening the URL")
soup = BeautifulSoup(page, 'html.parser')
content = soup.find('div', {"class": "sp-m-box-section"})
article = []
for url in urls:
article = article.append(content) #here I am completely unsure how to handle it
print(article)
感謝您的任何想法。
uj5u.com熱心網友回復:
這能解決你的問題嗎?
article = []
for url in urls:
try:
page = urlopen(url)
except:
print("Error opening the URL")
soup = BeautifulSoup(page, 'html.parser')
content = soup.find('div', {"class": "sp-m-box-section"})
article.append(content)
print(article)
uj5u.com熱心網友回復:
這里很少有問題。
article您在每次迭代后通過宣告覆寫您的串列article=[]。因此,即使您追加,它也將始終有一個空串列。在最后一次迭代之后,它不會創建article=[],給你留下它附加的最后一個東西。- 為什么要遍歷 url 兩次?
- 我改變了它以處理
try/except不同的情況。
基本上,嘗試閱讀頁面。如果沒有,則引發錯誤并繼續到下一個 url(如果無法讀取 html,則處理 html 毫無意義......另外你也會在那里得到一個錯誤)
試試這個:
article = []
for url in urls:
try:
page = urlopen(url)
except:
print("Error opening the URL")
continue
soup = BeautifulSoup(page, 'html.parser')
content = soup.find('div', {"class": "sp-m-box-section"})
article.append(content.text) # <- here I'm assuming you want the actual text/content, not the html
print(article)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/456867.html
上一篇:無法創建用于將多個變數轉換為as.factor的for回圈
下一篇:向Set<String>添加回應
