【发布时间】:2021-03-30 11:40:02
【问题描述】:
我正在尝试从一个本地网站获取产品名称及其价格。
网站是动态加载的,因此 requests 不支持它。我正在使用硒和美丽的汤。
但是它会重复计算每个产品(我为同一产品获得 2 个链接),有什么解决方案吗?
此外,在获取产品链接后,我需要获取产品信息(例如,名称和价格),但它再次计算产品并且不获取名称和价格。
我的代码:
import pandas as pd
from time import sleep
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from bs4 import BeautifulSoup
productlinks = []
baseurl = "https://www.technodom.kz/"
options = Options()
options.headless = True
driver = webdriver.Chrome(r"C:\path\to\chromedriver.exe", options=options)
for x in range(1, 5):
driver.get(
f"https://www.technodom.kz/bytovaja-tehnika/uhod-za-odezhdoj/stiral-nye-mashiny/f/brands/lg/brands/samsung?page={x}"
)
# Wait for the page to fully render
sleep(3)
soup = BeautifulSoup(driver.page_source, "lxml")
product_list = soup.find_all("li", class_="ProductCard")
for item in product_list:
for link in item.find_all("a", href=True):
productlinks.append(baseurl + link["href"])
print(productlinks)
wmlist = []
for link in productlinks:
driver.get(link)
soup = BeautifulSoup(driver.page_source, "lxml")
print(link)
name = soup.find('h1', class_='ProductHeader-Title').text.strip()
price = soup.find('p', class_='ProductPrice ProductInformation-Price').text.strip()
wm = {
'Model':name,
'Price': price
}
wmlist.append(wm)
print('Saving:', wm['Model'])
df = pd.DataFrame(wmlist)
df.to_excel("TD pricesTEST.xlsx", sheet_name='TEW', index=False)
【问题讨论】:
-
productlinks未定义,您正在使用pandas但没有导入。 -
productlinks 可能应该是 product_links。 item.find_all("a", href=True) 也会多次返回相同的 URL,因为它是 HTML!您可以定位正确的标签或在追加之前使用 IF 语句检查 url 是否唯一。
-
其实productlinks已经定义好了,我导入了pandas,在代码中添加了。
标签: python selenium selenium-webdriver web-scraping beautifulsoup