使用 beautifulsoup 在不同的选项卡中打开产品页面以获取亚马逊中输入的搜索结果

我对 python 很陌生,对网络抓取也很陌生——目前正在阅读 Al Sweigart 的书《使用 Python 自动化无聊的东西》,并且有一个建议的练习作业,基本上是制作一个程序来执行此操作:

  • 接受产品输入以在亚马逊中搜索

  • 使用 requests.get() 和 .text() 获取该搜索页面的 html

  • 使用 beautifulsoup 在 html 中搜索表示产品页面链接的 css 选择器

  • 在单独的选项卡中,打开搜索结果前五名产品的选项卡

这是我的代码:

#! python3

# Searches amazon for the inputted product (either through command line or input) and opens 5 tabs with the top 

# items for that search. 


    import requests, sys, bs4, webbrowser

    if len(sys.argv) > 1: # if there are system arguments

        res = requests.get('https://www.amazon.com/s?k=' + ''.join(sys.argv))

        res.raise_for_status

    else: # take input

        print('what product would you like to search Amazon for?')

        product = str(input())

        res = requests.get('https://www.amazon.com/s?k=' + ''.join(product))

        res.raise_for_status

    

    # retrieve top search links:

    soup = bs4.BeautifulSoup(res.text, 'html.parser')

    

    print(res.text) # TO CHECK HTML OF SITE, GET RID OF DURING ACTUAL PROGRAM

    # open a new tab for the top 5 items, and get the css selector for links 

    # a list of all things on the downloaded page that are within the css selector 'a-link-normal a-text-normal'

    linkElems = soup.select('a-link-normal a-text-normal') 

    

    numOpen = min(5, len(linkElems))

    for i in range(numOpen):

        urlToOpen = 'https://www.amazon.com/' + linkElems[i].get('href')

        print('Opening', urlToOpen)

        webbrowser.open(urlToOpen)

我想我已经选择了正确的 css 选择器(“a-link-normal a-text-normal”),所以我认为问题在于 res.text() - 当我打印以查看它的外观时,当我在 chrome 中使用检查元素查看同一站点时,html 内容似乎不完整,或者包含实际 html 的内容。此外,这些 html 都不包含任何内容,例如“a-link-normal a-text-normal”。


Cats萌萌
浏览 105回答 1
1回答

慕后森

这是一个经典案例,如果您尝试使用像 BeautifulSoup 这样的爬虫直接抓取网站,您将找不到任何东西。该网站的工作方式是,首先将初始代码块下载到您的浏览器,就像您添加的一样,big pencil然后通过 Javascript,加载页面上的其余元素。您需要先使用Selenium Webdriver加载页面,然后从浏览器中获取代码。在正常意义上,这相当于您打开浏览器的控制台,转到“元素”选项卡并查找您提到的类。要查看差异,我建议您查看页面的源代码并与“元素”选项卡中的代码进行比较在这里,您需要使用 BS4 获取加载到浏览器的数据from selenium import webdriverbrowser = webdriver.Chrome("path_to_chromedriver") # This is the Chromedriver which will open up a new instance of a browser for you. More info in the docsbrowser.get(url) # Fetch the URL on the browsersoup = bs4.BeautifulSoup(browser.page_source, 'html.parser') # Now load it to BS4 and go on with extracting the elements and so on这是了解 Selenium 的非常基本的代码,但是,在生产用例中,您可能需要使用像PhantomJS这样的无头浏览器
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python