Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/288.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 复制xpath元素在Python上不起作用_Javascript_Python_Html_Selenium - Fatal编程技术网

Javascript 复制xpath元素在Python上不起作用

Javascript 复制xpath元素在Python上不起作用,javascript,python,html,selenium,Javascript,Python,Html,Selenium,我尝试了一些访问twitter>的python代码来复制“立即发生”文本。但它不起作用 import webbrowser print("Visiting Twitter.com...") webbrowser.get('C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s').open_new('https://twitter.com') content = webbrowser.find_eleme

我尝试了一些访问twitter>的python代码来复制“立即发生”文本。但它不起作用

import webbrowser

print("Visiting Twitter.com...")
webbrowser.get('C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s').open_new('https://twitter.com')
content = webbrowser.find_element_by_xpath('//*[@id="react-root"]/div/div/div/main/div/div/div/div[1]/div[2]/div[1]/span').text
错误: 回溯(最近一次呼叫最后一次): 文件“C:/Users/Admin/PycharmProjects/pythonProject/main.py”,第5行,在 content=webbrowser。通过xpath('/*[@id=“react root”]/div/div/div/main/div/div/div/div/div[1]/div[2]/div[1]/span')查找元素。text
AttributeError:模块“webbrowser”没有属性“通过xpath查找元素”

您没有初始化浏览器
您必须执行类似于
driver=new ChromeDriver()的操作第一个。
此外,在从元素读取文本之前,应该添加一些等待条件,比如
wait.until(ExpectedConditions.visibilityOfElementLocated(element))

我介绍的代码在
Java
中,但在
Python

中非常类似。当我查看webbrowser.py文件中的源代码时,我看不到任何与“find_element_by_xpath”属性相关的内容,因此我得到了这个错误

Traceback (most recent call last):
  File "/Users/burakhanaksoy/Desktop/untitled folder/main.py", line 5, in <module>
    content = webbrowser.find_element_by_xpath('//*[@id="react-root"]/div/div/div/main/div/div/div/div[1]/div[2]/div[1]/span').text
AttributeError: module 'webbrowser' has no attribute 'find_element_by_xpath'
回溯(最近一次呼叫最后一次):
文件“/Users/burakhanaksoy/Desktop/untitled folder/main.py”,第5行,在
content=webbrowser。通过xpath('/*[@id=“react root”]/div/div/div/main/div/div/div/div/div[1]/div[2]/div[1]/span')查找元素。text
AttributeError:模块“webbrowser”没有“通过xpath查找元素”属性
我的建议是,如果您想使用xpath,就使用selenium。而且,您应该避免使用div/div/div类型的XPath,因为一旦twitter在其中添加了另一个div,您的代码就很容易被破坏

如果您想通过xpath查找“立即发生”文本,应该使用类似于
/*[contains(text(),“立即发生”)]


你可以从->

开始,我个人讨厌使用XPath,因为它让人困惑,并且会给我带来很多不必要的错误

我总是使用CSS选择器,因为它更简单、更可靠

webbrowser.find_element_by_css_selector('put_css_selector_here')

如果您不知道css选择器是如何工作的

您有什么错误?你能分享错误吗output@burakhan-我也更新了错误。请重新检查。@silva2021我的回答解决问题了吗?