我对 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”。
慕后森
相关分类