python - 使用 xpath 查看要抓取的特定元素
问题描述
我正在尝试从网站scamadviser.com 获取一些信息。特别是我对盾牌中的最终分数感兴趣(例如,对于 stackoverflow.com,检查盾牌中的值是 100%)。我试图检查它,我看到路径是:
我做了
def scam(df):
chrome_options = webdriver.ChromeOptions()
trust=[]
country = []
isp_country = []
urls=['stackoverflow.com','GitHub.com']
driver=webdriver.Chrome('mypath',chrome_options=chrome_options))
for x in urls:
wait = WebDriverWait(driver, 20)
response=driver.get('https://www.scamadviser.com/check-website/'+x)
try:
wait = WebDriverWait(driver, 30)
t=driver.execute_script("arguments[0].scrollTop = arguments[0].scrollHeight", driver.find_element_by_xpath("//div[contains(@class,'trust__overlay shield-color--green') and contains(text(),'icon')]")).get_attribute('innerText')
trust.append(t)
c=driver.execute_script("arguments[0].scrollTop = arguments[0].scrollHeight", driver.find_element_by_xpath("//div[contains(@class,'block__col') and contains(text(),'Country')]")).get_attribute('innerText')
country.append(c)
ic=driver.find_element_by_xpath("//div[contains(@class,'block__col') and contains(text(),'ISP')]").get_attribute('innerText')
isp_country.append(ic)
except:
trust.append("Error")
country.append("Error")
isp_country.append("Error")
# Create dataframe
dict = {'URL': urls, 'Trust':trust, 'Country': country, 'ISP': isp_country}
df=pd.DataFrame(dict)
driver.quit()
return df
但是创建的数据框仅包含Errors
(即,它仅执行except
中的try/except
)。
我不明白错误是否是由于 try/except 和/或我查看元素的方式(使用 xpath)造成的。任何帮助都会很棒。谢谢
解决方案
根据 OP 的响应和此特定票证,trusted score
要从 OP 提到的网站获取,以下xpath
有1/1 matching node in HTML DOM.
Xpath:-
//div[text()='Trustscore']/../following-sibling::div/descendant::div[@class='icon']
您无需滚动查看此 Web 元素,因为一旦启动 Windows,可信分数就在 Selenium 视图端口中。
像这样使用它explicit waits
:
trusted_score = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[text()='Trustscore']/../following-sibling::div/descendant::div[@class='icon']")))
print(trusted_score.text)
为此,您还需要导入。
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
PS:确保 Selenium windows 以全屏模式启动。
driver.maximize_window()
更新 1:
data = {'URL': urls,
'Trust': trust,
'Country': country,
'ISP': isp_country}
df = pd.DataFrame.from_dict(data)
推荐阅读
- swift - 添加弱子视图导致iOS14崩溃
- git - 无法使用 Jenkins 配置私有 Git 服务器
- libgit2 - 使用libgit2同时读取存储库多次的最佳方法,性能/内存明智?
- python - TypeError: int() 参数必须是字符串、类似字节的对象或数字,而不是“NoneType”深度学习
- c++ - 在字符串中查找项目并说何时找到 - c++
- python - 创建一个新文件夹并将其设置为 selenium 中的默认下载
- ruby - 是否有一个 Ruby 单线器来 join() 嵌套的 Ruby 数组,内部/外部数组有不同的 join() 字符串?
- opengl - 在 Ubuntu 18.04 中链接 glfw3 的问题
- apache-flink - 操作依赖什么规则来生成新的事件时间戳
- go - 在golang中反射和类型切换后调用接口方法