我正试图使用Python从百思买网站上获取内容,但在国家选择页面上遇到了最初的障碍。第一次访问百思买时,该网站要求用户选择一个国家,该国家似乎是通过JavaScript管理的。我想通过此页面自动访问网站的主要内容。
我目前正在使用BeautifulSoup进行抓取,但我知道它不处理JavaScript。如果可能的话,我希望避免使用Selenium或其他浏览器自动化工具。
有没有一种方法可以使用Selenium以外的库,例如通过直接HTTP请求,用Python模拟国家选择?
任何绕过或模拟国家选择的指导或替代建议都将不胜感激!
我的代码片段:
def scrape_bestbuy(product_name):
url = f"https://www.bestbuy.com/site/searchpage.jsp?st={product_name.replace(' ', '+')}"
response = requests.get(url, headers=get_random_user_agent())
soup = BeautifulSoup(response.text, 'html.parser')
try:
product = soup.select_one('.sku-title a').text.strip()
price = soup.select_one(".pricing-price div[data-testid='large-price'] .priceView-customer-price > span:nth-child(1)").text
return {'Site': 'Bestbuy.com', 'Item title name': product, 'Price(USD)': price}
except AttributeError:
return {'Site': 'Bestbuy.com', 'Item title name': 'No Product Found', 'Price(USD)': 'N/A'}