我正在嘗試從包含在型別標題、標題或段落標簽中的網頁中抓取文本。當我嘗試下面的代碼時,我會根據 url 的來源得到不同的結果。當我嘗試一些來源(例如維基百科或路透社)時,代碼或多或少都可以正常作業,并且至少可以找到所有文本。對于其他來源(例如 Politico、The Economist),我開始錯過網頁中包含的很多文本。
我正在使用遍歷演算法遍歷樹并檢查標簽是否“感興趣”。也許find_all(True, recursive=False)是由于某種原因丟失了隨后包含我正在尋找的文本的孩子?我不確定如何調查。或者也許某些網站以某種方式阻止了抓取?但是為什么我可以從經濟學家那里刮掉一段呢?
下面的代碼為我復制了問題 - 您應該看到維基百科頁面 ( urls[3]) 按需要列印,政治 ( urls[0]) 缺少文章中的所有文本,經濟學家 ( urls[1]) 缺少除一個段落之外的所有內容。
from bs4 import BeautifulSoup
import requests
urls = ["https://www.politico.com/news/2022/01/17/democrats-biden-clean-energy-527175",
"https://www.economist.com/finance-and-economics/the-race-to-power-the-defi-ecosystem-is-on/21807229",
"https://www.reuters.com/world/significant-damage-reported-tongas-main-island-after-volcanic-eruption-2022-01-17/",
"https://en.wikipedia.org/wiki/World_War_II"]
# get soup
url = urls[0] # first two urls don't work, last two do work
response = requests.get(url)
soup = BeautifulSoup(response.text, features="html.parser")
# tags with text that i want to print
tags_of_interest = ['p', 'title'] ['h' str(i) for i in range(1, 7)]
def read(soup):
for tag in soup.find_all(True, recursive=False):
if (tag.name in tags_of_interest):
print(tag.name ": ", tag.text.strip())
for child in tag.find_all(True, recursive=False):
read(child)
# call the function
read(soup)
uj5u.com熱心網友回復:
BeautifulSoup將按照此處find_all()的答案以 DFT(深度優先遍歷)的順序回傳標簽串列。這允許輕松訪問所需的元素。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/417671.html
標籤:
上一篇:從帶有有效負載的SolisPro(Ginlong)平臺獲取異步資料時出錯
下一篇:從html中提取資料并生成CSV
