我认为你的代码花费这么长时间的原因是因为循环list_gen
在循环时向网页发送一堆请求。如果您在循环中设置断点,并在开发工具运行时查看浏览器的网络页面,您将看到大量请求从循环开始。我认为这是因为当硒向下滚动时页面正在加载新元素。
据我所知,如果你想让它更快,你应该使用其他东西。我的建议是使用美丽的汤。
from selenium import webdriver
from time import time
from bs4 import BeautifulSoup
driver = webdriver.Chrome()
i = time()
driver.get('https://nameberry.com/popular_names/US')
soup = BeautifulSoup(driver.page_source, 'html5lib')
boys_names = [x.getText() for x in soup.find_all("td", {"class", "boys"})]
girls_names = [x.getText() for x in soup.find_all("td", {"class", "girls"})]
e = time()
print(e - i) # gives ~ 14 sec for me
这会立即获取网页的整个源代码并对其进行解析,而不必使用 css 选择器返回的 webdriver 对象列表。
如果您不使用 selenium 浏览器执行其他任何操作而只想获取名称,则可以使用 requests 更快地获取页面源,因为您不需要加载 selenium 浏览器。
import requests
i = time()
response = requests.get('https://nameberry.com/popular_names/US')
soup = BeautifulSoup(response.content, 'html5lib')
boys_names = [x.getText() for x in soup.find_all("td", {"class", "boys"})]
girls_names = [x.getText() for x in soup.find_all("td", {"class", "girls"})]
e = time()
print(e - i) # gives ~ 3.2 sec