[英]Why is my for loop failing halfway through my list? Selenium webdriver, driver.find_element_by_xpath
I have a list of 10 linkedin urls that I am running.我有一个我正在运行的 10 个linkedin url 的列表。 For 8 of the urls, the code works perfectly.对于其中的 8 个网址,代码运行良好。 But it consistently fails during the 9th iteration.但它在第 9 次迭代期间始终失败。
This is my traceback:这是我的回溯:
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)
Relevant code:相关代码:
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'))
Why would the code stop working?为什么代码会停止工作? I checked the 9th url , and the xpath is the same for images
我检查了第 9 个 url , images
的 xpath 是相同的
It's failing on它失败了
images = driver.find_element_by_xpath('// img[ @ id = "ember51"]')
The element with the id of "ember51" is a div, so change it to this: id为“ember51”的元素是一个div,所以改成这样:
images = driver.find_element_by_xpath('// div[ @ id = "ember51"]/img')
This way when you try to get the src attribute on the next line, it will work.这样,当您尝试获取下一行的 src 属性时,它将起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.