簡體   English   中英

使用 BeautifulSoup 獲取所有按鈕的列表,但未顯示所需按鈕

[英]Using BeautifulSoup to get list of all buttons, but needed buttons are not displaying

我正在使用 BeautifulSoup 來獲取頁面上所有按鈕對象的列表,以便我可以選擇一個稍后與之交互。 我正在使用下面的代碼,但在網站上沒有顯示添加到購物車按鈕。 如果我檢查元素,我可以看到它是一個按鈕。

我試圖以盡可能通用的方式做到這一點,以便我可以為多個網站使用相同的代碼。 因此,理想情況下,我不想使用特定屬性來查找該按鈕,我想創建一個 function,它允許我通過顯示所有按鈕並隨后縮小范圍來輕松找到任何頁面上的任何所需按鈕。

知道為什么我無法在此代碼中找到添加到購物車按鈕嗎?

from bs4 import BeautifulSoup

page = requests.get('https://www.target.com/p/madden-nfl-21-xbox-one-series-x/-/A-79800769')
data = page.text
soup = BeautifulSoup(data, 'html.parser')
buttons = soup.find_all('button')
for button in buttons:
    print(button)

您將需要selenium因為按鈕是由 JS 生成的。 請閱讀答案以獲取更多解釋。

代碼:

from selenium import webdriver
from bs4 import BeautifulSoup
from selenium.webdriver.chrome.options import Options

# start chrome in headless (not visible) mode
options = Options()
options.headless = True
driver = webdriver.Chrome(options=options)

# go to url and wait until page is loaded
url = 'https://www.target.com/p/madden-nfl-21-xbox-one-series-x/-/A-79800769'
driver.get(url)

# get html of page and close webdriver
html = driver.page_source
driver.quit()

# do whatever you want with buttons
soup = BeautifulSoup(html, 'html.parser')
buttons = soup.find_all('button')
print(*buttons, sep='\n')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM