首页 > 解决方案 > 通过 XPath 转换为来自 Selenium Find Element 的请求

问题描述

我正在使用 Selenium Webdriver 使用“通过 XPath 查找元素”从网站中提取价格,然后将其转换为文本。现在我需要改用 Requests 而不是 Selenium,而且我似乎遇到了多个问题。

有人可以帮我将此代码转换为请求格式吗?

listprice = browser.find_element_by_xpath("//span[@class='title price']")
price = listprice.text
print(price)

我尝试使用 QHarr 下面提到的方法,但出现以下错误:

AttributeError: 'NoneType' object has no attribute 'text'

标签: pythonxpathpython-requests

解决方案


如果您确定请求响应中存在该元素

import requests
from bs4 import BeautifulSoup as bs

r = requests.get(url) # < insert your url. Headers may be required.
soup = bs(r.content, 'html.parser')
price = soup.select_one('span[class="title price"]').text
print(price)

推荐阅读