代码之家  ›  专栏  ›  技术社区  ›  Tomer Fikler

如何在没有硒的情况下使用Python处理百思买登录页上的国家选择?

  •  1
  • Tomer Fikler  · 技术社区  · 2 年前

    我正试图使用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'}
    
    1 回复  |  直到 2 年前
        1
  •  1
  •   mcsoini    2 年前

    当你在浏览器中选择USA时,你会看到它添加了 &intl=nosplash 到URL。因此,运行以下程序实际上似乎可以工作并打印 '$159.99' :

    from bs4 import BeautifulSoup
    import requests 
    
    product_name = "vacuum"
    
    url = f"https://www.bestbuy.com/site/searchpage.jsp?st={product_name.replace(' ', '+')}&intl=nosplash"
    response = requests.get(url, headers={'User-agent': 'Mozilla/5.0'})
    
    soup = BeautifulSoup(response.text, 'html.parser')
    
    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
    
    print(price)