为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Cats萌萌 2023-05-16 14:55:38
我对 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”。
查看完整描述

1 回答

?
慕后森

TA贡献1802条经验 获得超5个赞

这是一个经典案例,如果您尝试使用像 BeautifulSoup 这样的爬虫直接抓取网站,您将找不到任何东西。

该网站的工作方式是,首先将初始代码块下载到您的浏览器,就像您添加的一样,big pencil然后通过 Javascript,加载页面上的其余元素。

您需要先使用Selenium Webdriver加载页面,然后从浏览器中获取代码。在正常意义上,这相当于您打开浏览器的控制台,转到“元素”选项卡并查找您提到的类。

要查看差异,我建议您查看页面的源代码并与“元素”选项卡中的代码进行比较

在这里,您需要使用 BS4 获取加载到浏览器的数据

from selenium import webdriver


browser = 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 docs


browser.get(url) # Fetch the URL on the browser


soup = bs4.BeautifulSoup(browser.page_source, 'html.parser') # Now load it to BS4 and go on with extracting the elements and so on

这是了解 Selenium 的非常基本的代码,但是,在生产用例中,您可能需要使用像PhantomJS这样的无头浏览器


查看完整回答
反对 回复 2023-05-16
  • 1 回答
  • 0 关注
  • 102 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信