【发布时间】:2020-09-08 12:04:53
【问题描述】:
我正在做一个课程项目,但我从亚马逊获得的数据缺少产品名称、价格和类别。由于我没有用于 API 的 AWS 帐户,因此我决定根据我拥有的 ASIN(产品 ID)来抓取此信息。但我对网络抓取还不太了解(例如 XML 结构)。代码的抓取部分改编自一个功能性论坛抓取项目,但在这里不起作用。
我还尝试了 BeautifulSoup,我什至专门从一个类似的亚马逊项目中找到了它,但它也不起作用。由于 Selenium 更通用,我真的更喜欢以这种方式学习。所以,这里是代码,没有功能的 XPath:
from selenium import webdriver
from random import randint
asin_set = ['0151004714', '0380709473','0511189877', '0528881469', '0545105668', '0557348153', '0594033926', '0594296420', '0594450268', '0594451647', '0594459451', '0594481902', '059449771X']
driver = webdriver.Chrome()
list_of_dicts[:] = []
print('This is gonna be LEGEN... wait for it:')
for i in asin_set[:5]:
url = f'https://www.amazon.com/gp/product/{i}'
driver.get(url)
product_info = {}
product_info['asin'] = i
try:
name = driver.find_elements_by_xpath('//*[@id="' + x + '"]') #<---
product_info['name'] = name.text('productTitle') #<---
except:
product_info['name'] = 0
try:
price = driver.find_elements_by_xpath('//*[@id="' + x + '"]') #<---
product_info['price'] = price.text #<---
except:
product_info['price'] = 0
try:
category = driver.find_elements_by_xpath('//*[@id="' + x + '"]/ul/li[5]/span/a') #<---
product_info['category'] = category.get_attribute('wayfinding-breadcrumbs_feature_div') #<---
except:
product_info['category'] = 0
list_of_dicts.append(product_info) # Append scrape to dictionary
print(str(len(list_of_dicts)) + ' . ', end='') # print the current length of the scrapes
sleep(randint(1,2)) # Sleep 1 or 2 seconds in bewteen scrapes
print('DARY!')
单元格运行良好,浏览器打开每个页面。但是事情没有被正确访问或存储,我得到 list_of_dicts 的结果是这样的:
[{'asin': '0151004714', 'name': 0, 'price': 0, 'category': 0},
{'asin': '0380709473', 'name': 0, 'price': 0, 'category': 0},
{'asin': '0511189877', 'name': 0, 'price': 0, 'category': 0},
{'asin': '0528881469', 'name': 0, 'price': 0, 'category': 0},
{'asin': '0545105668', 'name': 0, 'price': 0, 'category': 0}]
【问题讨论】:
-
这里不工作你到底卡在哪里了?
-
您是否尝试过打印错误信息?由于所有零都来自您拥有的
execpt-clauses,因此这是一个很好的起点。我的第一个想法是变量x。我没有看到它在任何地方被定义,这会抛出一个NameError-exception -
没有错误。代码很好。我认为问题在于 XPath 是错误的,因此无法检索任何值。所有 XPath 都用
-
那么你的变量
x是什么?如果没有错误,则 x 必须填写,并且是 XPath 的一部分。所以 x 可能仍然是问题所在。但是,您所有的值都返回为 0,恰好在您的except中,所以您确定没有错误,或者您是否因为尝试而没有收到错误消息,除了? -
我带走了第一层的“尝试”。没有不同。与此处的代码一样,该 asin 已为所有人正确注册。我不能排除其他“尝试”,因为许多产品不再可用,所以它总是会出错。变量“x”用于另一个项目(我在问题中提到的论坛),完全一样,没有问题,所以我真的认为 x 本身不是问题,而是它所指的问题,在XPath,或者它是如何存储的,因为这些部分我不太了解。