繁体   English   中英

为什么我的 for 循环在我的列表中途失败? Selenium webdriver,driver.find_element_by_xpath

[英]Why is my for loop failing halfway through my list? Selenium webdriver, driver.find_element_by_xpath

我有一个我正在运行的 10 个linkedin url 的列表。 对于其中的 8 个网址,代码运行良好。 但它在第 9 次迭代期间始终失败。

这是我的回溯:

Traceback (most recent call last):
  File "/Users/yu/PycharmProjects/linkedin/hello.py", line 97, in <module>
    images = driver.find_element_by_xpath('// img[ @ id = "ember51"]')
  File "/Users/yu/PycharmProjects/linkedin/venv/lib/python3.8/site-packages/selenium/webdriver/remote/webdriver.py", line 394, in find_element_by_xpath
    return self.find_element(by=By.XPATH, value=xpath)
  File "/Users/yu/PycharmProjects/linkedin/venv/lib/python3.8/site-packages/selenium/webdriver/remote/webdriver.py", line 976, in find_element
    return self.execute(Command.FIND_ELEMENT, {
  File "/Users/yu/PycharmProjects/linkedin/venv/lib/python3.8/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "/Users/yu/PycharmProjects/linkedin/venv/lib/python3.8/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"// img[ @ id = "ember51"]"}
  (Session info: chrome=80.0.3987.122)

相关代码:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from parsel import Selector

ChromeOptions = webdriver.ChromeOptions()
ChromeOptions.add_argument('--disable-browser-side-navigation')
driver = webdriver.Chrome('/Users/yu/Downloads/chromedriver')

linkedin_urls=driver.find_elements_by_xpath('//*[@id="rso"]/div[1]/div/div')
linkedin_urls=[url.find_element_by_xpath('div/div/div[1]/a').get_attribute('href') for url in linkedin_urls]

for linkedin_url in (linkedin_urls):
    driver.get(linkedin_url)
    sel = Selector(text=driver.page_source)

images = driver.find_element_by_xpath('// img[ @ id = "ember51"]')
print(images.get_attribute('src'))

为什么代码会停止工作? 我检查了第 9 个 urlimages的 xpath 是相同的

它失败了

images = driver.find_element_by_xpath('// img[ @ id = "ember51"]')

id为“ember51”的元素是一个div,所以改成这样:

images = driver.find_element_by_xpath('// div[ @ id = "ember51"]/img')

这样,当您尝试获取下一行的 src 属性时,它将起作用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM