gpt4 book ai didi

python - Selenium 脚本向元素返回 null

转载 作者:太空宇宙 更新时间:2023-11-03 14:23:05 47 4
gpt4 key购买 nike

我正在运行这个脚本,它在找到 id 后获取一些内容,该 id 将由 AJAX 调用填充,它应该转到第二个 URL。转到第二个 URL 后,没有找到任何具有相同 id 的内容。

代码片段在这里:

from selenium import webdriver
from selenium.webdriver.remote.webelement import WebElement
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
import json
from selenium.webdriver.support import expected_conditions as EC

path_to_chromedriver = 'D:\Mangilal\Downloads\chromedriver_win32\chromedriver.exe' #Change path
as needed.
browser = webdriver.Chrome(executable_path=path_to_chromedriver)
#Sample list of URLs.

lists_of_url = ['http://facebook.com', 'http://twitter.com',
'http://google.com', 'http://youtube.com',
'http://linkedin.com', 'http://wordpress.org',
'http://instagram.com', 'http://pinterest.com',
'http://wikipedia.org', 'http://wordpress.com',
'http://slideshare.net', 'http://e-recht24.de',
'http://washingtonpost.com', 'http://etsy.com',
'http://eventbrite.com', 'http://archive.org',
'http://cpanel.net', 'http://miibeian.gov.cn',
'http://sourceforge.net', 'http://telegraph.co.uk',
'http://ameblo.jp', 'http://amazon.co.uk',
'http://ebay.com', 'http://fc2.com',
'http://free.fr', 'http://bing.com']


for i in range(10):
url = 'https://www.shareaholic.com/sharecounter?url=' + lists_of_url[i]
browser.get(url)
element = WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.XPATH, '//*[@id="container"]/div[1]/div[2]/div[3]/div/div/h1/span')))
str = ''
#Finding element here.
count = browser.find_element_by_xpath('//*[@id="container"]/div[1]/div[2]/div[3]/div/div/h1/span')
str = count.get_attribute('innerHTML')
print(str)
其输出如图所示,它获取该 null 值之后的第一个 URL 的内容:

Image showing the output

最佳答案

首先,str是Python的内置函数。不要将其用作变量。
其次,应该对查询字符串进行编码。
第三,您应该等到元素可见。请参阅下面我的代码。

from urllib.parse import urlencode
...
for i in range(10):
url = 'https://www.shareaholic.com/sharecounter?' + urlencode({"url":lists_of_url[i]})
driver.get(url)
element = WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.XPATH, '//*[@id="container"]/div[1]/div[2]/div[3]/div/div/h1/span')))
txt = ''
#Finding element here.
count = driver.find_element_by_xpath('//*[@id="container"]/div[1]/div[2]/div[3]/div/div/h1/span')
txt = count.get_attribute('innerHTML')
print(txt)

关于python - Selenium 脚本向元素返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47822369/

47 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com