我正在使用 BeautifulSoup 和 Selenium 来提取 Web 数据(beautifulsoup 来解析 HTML 页面和 Selenium 来单击 Next 以进入页面上的下一个项目列表)。
我需要代码做的是:
我当前的代码正在做的是:
我认为这是因为我在代码中以错误的顺序使用了一些步骤。下面是一个精简版。我做错了什么可见吗?
import requests
from bs4 import BeautifulSoup
from csv import writer
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
import time
from selenium.webdriver.common.by import By
URL = "https://www.theitdepot.com/products-Motherboards_C13.html"
wd = webdriver.Chrome(ChromeDriverManager().install())
wd.get(URL)
running = True
while running:
page = requests.get(URL, verify = False)
soup = BeautifulSoup(page.content, "html.parser")
results = soup.find(id="filter_display")
item_elements = results.find_all("div", class_="product-details text-md-left flex-grow-1")
with open('data.csv', 'a', encoding='utf8', newline='') as f:
thewriter = writer(f)
for item_element in item_elements:
#code to retrieve information and write to CSV here
name_element = item_element.find("div", class_="card-text px-2 py-1 font-size85 product_title")
name = str(name_element.text)
print (name)
next = wd.find_element(by=By.XPATH, value="//*[contains(text(), 'Next →')]")
wd.execute_script("arguments[0].click();", next)
time.sleep(10) #prevent ban
(注意:我知道这目前是一个无限循环,我打算添加逻辑以知道所有页面何时完成)
对于这个简单的任务,您可以使用 Selenium 本身而不是 BeautifulSoup。此外,您可以将产品名称保存在列表中并使用numpy
. 我更喜欢 numpy,因为它可以让您用with open(...) as f: etc.
简单的行替换代码块。
number_of_pages_to_scrape = 5
names = []
for i in range(number_of_pages_to_scrape):
items = driver.find_elements(By.CSS_SELECTOR, "div[class='card-text px-2 py-1 font-size85 product_title']")
for item in items:
print(item.text)
names.append(item.text)
driver.find_element(By.XPATH, "//*[contains(text(), 'Next')]").click()
time.sleep(10)
import numpy
numpy.savetxt("data.csv", names, fmt ='%s')
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句