我从Products页面中删除产品链接<a href="">
,并将它们存储在数组hrefs
中
from bs4 import BeautifulSoup
from selenium import webdriver
import os
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--headless")
service = webdriver.chrome.service.Service(executable_path=os.getcwd() + "./chromedriver.exe")
driver = webdriver.Chrome(service=service, options=chrome_options)
driver.set_page_load_timeout(900)
link = 'https://www.catch.com.au/seller/vdoo/products.html?page=1'
driver.get(link)
soup = BeautifulSoup(driver.page_source, 'lxml')
product_links = soup.find_all("a", class_="css-1k3ukvl")
hrefs = []
for product_link in product_links:
href = product_link.get("href")
if href.startswith("/"):
href = "https://www.catch.com.au" + href
hrefs.append(href)
大约有36个链接存储在所有36个产品在页面上的数组,然后我开始从hrefs
挑选每个链接,并前往它,并从每个链接删除进一步的数据.
products = []
for href in hrefs:
driver.get(href)
soup = BeautifulSoup(driver.page_source, 'lxml')
title = soup.find("h1", class_="e12cshkt0").text.strip()
price = soup.find("span", class_="css-1qfcjyj").text.strip()
image_link = soup.find("img", class_="css-qvzl9f")["src"]
product = {
"title": title,
"price": price,
"image_link": image_link
}
products.append(product)
driver.quit()
print(len(products))
但这花了太多时间.我已经设置了900秒,但超时了.问题:
- 在开始,现在,我只是从第一页提取产品链接,但我有更多的页面,如多达40页,每页36个产品.当我实现从所有页面获取数据时,它也超时.
- 然后在第二部分,当我使用这些链接,并取消每个链接,那么它也需要更多的时间. 我怎样才能减少这个程序的执行时间.我可以把节目分成几个部分吗?