【发布时间】:2020-11-26 19:16:02
【问题描述】:
我正在联系,因为我在调整一段代码时遇到了一些麻烦,该代码应该从亚马逊产品页面中抓取一些信息(标题、网址、产品名称等)。用于抓取训练的经典内容:)
所以我基本上是通过不同的函数来写的:
- 一个生成要抓取的 URL 的函数
- 一个跨不同元素导航并提取值的函数
最后我只运行我的驱动程序和beautifulsoup 并启动这两个函数。
然而,结果并不是我所期望的。我想检索一个有组织的 csv 文件,每个产品检索 1 行并将每个相关信息放入列中。尽管如此,我总是以 1 或 2 行结束,但不是所有页面的所有产品。
我认为这是来自我的汤以及未正确遍历所有项目的“for循环”(尽管我无法弄清楚究竟是什么)。
我想听听你对此的看法,你有什么线索吗?
非常感谢您的帮助
from bs4 import BeautifulSoup
from selenium import webdriver
import csv
#Function to generate URL with search KW & page nb
def get_url(search_term,page):
template = 'https://www.amazon.co.uk/s?k={}&page='+str(page)
search_term = search_term.replace(' ','+')
url = template.format(search_term)
return url
#Function to retrieve all data from the page
def extract_record(item):
atag = item.h2.a
#Retrieve product name
description = atag.text.strip()
#Retrieve product URL
url = 'https://www.amazon.co.uk' + atag.get('href')
#Retrieve sponsored status
try:
sponso_parent = item.find('span','s-label-popover-default')
sponso = sponso_parent.find('span', {'class': 'a-size-mini a-color-secondary', 'dir': 'auto'}).text
except AttributeError:
sponso = 'No'
#Retrieve price info
try:
price_parent = item.find('span','a-price')
price = price_parent.find('span','a-offscreen').text
except AttributeError:
return
#Retrieve avg product rating
try:
rating = item.i.text
except AttributeError:
rating = ''
#Retrieve review count (if monetary value, nill it due to missing value)
try:
review_count = item.find('span', {'class': 'a-size-base', 'dir': 'auto'}).text
except AttributeError:
review_count = ''
if "£" in review_count or "€" in review_count or "$" in review_count:
review_count = 0
result = (url, description, sponso, price, rating, review_count)
return result
record_final = []
#Loop through page nb
for page in range(1,3):
url = get_url('laptop',page)
print(url)
#Instantiate web driver & retrieve page content with BS (then loop through every product)
driver = webdriver.Chrome('\\Users\\rapha\\Desktop\\chromedriver.exe')
driver.get(url)
soup = BeautifulSoup(driver.page_source, 'html.parser')
final_soup = soup.find_all('div',{'data-component-type': 's-search-result'})
try:
for item in final_soup:
record = extract_record(item)
if record:
record_final.append(record)
except AttributeError:
print('error_record')
driver.close()
with open('resultsamz.csv','w', newline='', encoding='utf-8') as f:
writer = csv.writer(f)
writer.writerow(['url', 'description', 'sponso', 'price', 'rating','review_count'])
writer.writerow(record_final)
【问题讨论】:
-
两个页面上都有一个
Accept cookies弹出窗口。您的代码似乎没有解决这个问题, -
这如何阻止执行我描述的内容?尽管有 cookie 横幅,但 BS 检索到的源代码似乎正常
标签: python python-3.x web-scraping beautifulsoup amazon