我正在使用 BeautifulSoup 抓取一個網站,但 html 的輸出與通過 Web 瀏覽器顯示在頁面源上的不匹配。缺少一些標簽。下面是我的代碼:
URL = '<url>'
response = requests.get(URL, headers = header)
html_doc = BeautifulSoup(response, 'html.parser')
content = html_doc.find('div', attrs={'class':'content-wrapper'})
我不確定發生了什么,但它可能與事件監聽器有關。我在頁面源代碼上的這個標簽之后找到了它。
uj5u.com熱心網友回復:
如果問題是由 eventlistener 引起的,我建議您使用beautifulsoupwithselenium來抓取此網站。因此,讓我們selenium在發送請求時應用并獲取頁面源,然后用于beautifulsoup決議它。
請注意,使用 selenium 需要瀏覽器驅動程式。您可能會通過此鏈接找到(https://www.selenium.dev/documentation/getting_started/installing_browser_drivers/)。
使用 Firefox 的代碼示例:
from selenium import webdriver
URL = '<url>'
browser = webdriver.Firefox()
browser.get(URL)
html_doc = BeautifulSoup(browser.page_source, 'html.parser')
time.sleep(1)
browser.close()
content = html_doc.find('div', attrs={'class':'content-wrapper'})
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/377785.html
