【发布时间】:2021-09-10 01:17:40
【问题描述】:
我已经尝试了来自this 非常相似的帖子的所有解决方案,但不幸的是,虽然我没有收到任何有用的错误,我的文件夹中也没有任何 pdf 文件。
要更改配置以使 selenium 无头工作并下载到我想要的目录,我遵循了 post 和 this。
但是我什么也没看到。此外,交互执行与运行脚本时的行为也不同。交互执行时,我看不到任何错误,但也没有任何反应。运行脚本时出现一个不太有用的错误:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, f"a[href*={css_selector}']"))).click()
File "C----\selenium\webdriver\support\wait.py", line 80, in until
raise TimeoutException(message, screen, stacktrace)
selenium.common.exceptions.TimeoutException: Message:
有问题的网站是here。
我试图使工作的代码是 -
import requests
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
options = Options()
options.headless = True
uri = "http://affidavitarchive.nic.in/CANDIDATEAFFIDAVIT.aspx?YEARID=March-2017+(+GEN+)&AC_No=1&st_code=S24&constType=AC"
driver = webdriver.Firefox(options=options, executable_path=r'C:\\Users\\xxx\\geckodriver.exe')
profile = webdriver.FirefoxProfile()
profile.set_preference('browser.download.folderList', 2) # custom location
profile.set_preference('browser.download.manager.showWhenStarting', False)
profile.set_preference('browser.download.dir', r'C:\\Users\\xxx\\Downloads')
profile.set_preference('browser.helperApps.neverAsk.saveToDisk', 'application/pdf')
# Function that reads the table in the webpage and extracts the links for the pdfs
def get_links_from_table(uri):
html = requests.get(uri)
soup = BeautifulSoup(html.content, 'lxml')
table = soup.find_all('table')[-1]
candidate_affidavit_links = []
for link in table.find_all('a'):
candidate_affidavit_links.append(link.get('href'))
return candidate_affidavit_links
candidate_affidavit_links_list = get_links_from_table(uri)
driver.get(uri)
# iterate over the javascript links and try to download the pdf files
for js_link in candidate_affidavit_links_list:
css_selector = js_link.split("'")[1]
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, f"a[href*={css_selector}']"))).click()
driver.execute_script(js_link)
【问题讨论】:
-
我对 BeautifulSoup 几乎不熟悉,但也许您需要在
get_links_from_table方法中放置某种等待/延迟,以让数据加载类似于我们在 Selenium 中所做的操作?在html = requests.get(uri)之后在soup = BeautifulSoup(html.content, 'lxml')之前睡觉?或者可能是在那之后的一行? -
@Prophet 我不太确定。如果您检查网页,它非常轻巧,并且 pdf 链接始终是 javascript。您可以尝试打印
candidate_affidavit_links_list,您会看到链接已成功获取。所以我认为这可能不是问题。但我真的不知道说实话。 -
再一次,我不知道它是如何与 BeautifulSoup 一起工作的,但是对于 Selenium,任何页面更改/加载都比代码执行花费更多的时间,所以我们必须在每一步的地方使用某种等待页面已更改。
-
我做了一次
driver.get(uri)然后在最后一行你可以看到我有WebDriverWait(driver, 20)......是等待20 秒吗?要不要我加个试试? -
不,不需要。在
for js_link in candidate_affidavit_links_list:循环中,您正在等待一些元素可点击,但恐怕元素列表是空的,因为当您阅读它们时,页面仍未加载。或者类似的东西。
标签: javascript python python-3.x selenium selenium-webdriver