【发布时间】:2021-11-09 12:30:13
【问题描述】:
我有一个用于工作的网络爬虫,可以从我们的非公开网站下载给定过滤器的所有 pdf。我正在尝试命名文件 “ID 号 + 文件名 + 日期文件是 made.pdf” 我在 Try 语句中使用绝对 xPath 作为文件名,但它不起作用并且跳到异常。如果我错过了任何语法方面的内容,或者是否有更好的方法来实现这一点,我将不胜感激。我也复制了xPath,看看有没有经验的人可以给我相对的xPath使用
错误:
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"/html/body/div[1]/div[1]/div[4]/div/div[2]/div/div/div[2]/div/div/div[1]/div[1]/div[2]/h2"}
(Session info: chrome=93.0.4577.63)
HTML:
我的代码:
table_rows=driver.find_elements_by_xpath("//a[contains(@href, '#resources/details/?id=')]")
for link_elem in table_rows:
url = link_elem.get_attribute('href')
id_number= url[-8:]
driver.get(url)
try:
filename_first = driver.find_element_by_xpath('/html/body/div[1]/div[1]/div[4]/div/div[2]/div/div/div[2]/div/div/div[1]/div[1]/div[2]/h2').text.replace(':', '').replace(r'/', '-')
except:
filename_first = 'file.pdf'
#filename_first = driver.find_element_by_xpath('/html/body/div[1]/div[1]/div[4]/div/div[2]/div/div/div[2]/div/div/div[1]/div[1]/div[2]/h2').text.replace(':', '').replace(r'/', '-')
filename_final = id_number + filename_first #+ '.pdf'
css_thing = '#file > div:nth-child(1) > div.form-group.padding-xs-bottom > div > div > button.btn.btn-danger.get-download-url'
time.sleep(5)
download_button = driver.find_element_by_css_selector(css_thing)
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, css_thing))).click()
time.sleep(5)
link_data = driver.find_element_by_xpath("//a[contains(@href, 'https://s3.amazonaws.com')]")
url = link_data.get_attribute("href")
r = requests.get(url, allow_redirects=True)
open(filename_final, 'wb').write(r.content)
print("good")
【问题讨论】:
-
你不应该使用这些类型的动态 xpath
/html/body/div[1]/div[1]/div[4]/div/div[2]/div/div/div[2]/div/div/div[1]/div[1]/div[2]/h2 -
试试这个
//a//div[@class='flex-1 ellipsis padding-xs-right'] -
@NandanA 谢谢!现在当我运行 filename_first = driver.find_element_by_xpath("//a//div[@class='flex-1 ellipsis padding-xs-right']").text.replace(':', '').replace( r'/', '-') + '.pdf' 文件名就变成了.pdf
-
你能给我们示例pdf名称以查看
-
@NandanA 当然!目前使用该行代码的名称只是.pdf。然后当它迭代循环时,它只会覆盖该文件。当我从代码中删除 + '.pdf' 时,它只是用 Id_number 命名它们。哪个更好,但 id 更喜欢 Xpath 文本 +id_number+.pdf