我试图打印出一些住房价格,但在使用Xpath时遇到了问题。这是我的密码:
from selenium import webdriver
driver = webdriver.Chrome("my/path/here")
driver.get("https://www.realtor.com/realestateandhomes-search/?pgsz=10")
for house_number in range(1,11):
try:
price = driver.find_element_by_xpath("""//*[@id="
{}"]/div[2]/div[1]""".format(house_number))
print(price.text)
except:
print('couldnt find')
我在this网站上,试图打印出前十套房子的房价。你知道吗
我的结果是,对于所有说“新”的房子,它被作为价格而不是实际价格。但对于最底层的两个,没有新的标签,实际价格会被记录下来。你知道吗
如何使Xpath选择器选择数字而不是新的?你知道吗
您可以这样写,而无需加载图像,这可以提高您的抓取速度
你走对了路,你只是做了一个太脆弱的XPath。我会尽量使它更详细一点,而不依赖于索引和通配符。你知道吗
下面是XPath(我使用
id="1"
作为示例):下面是HTML(为了简洁起见,删除了一些属性/元素):
首先,将
*
通配符替换为您希望包含id="1"
的元素。这只是一种帮助XPath更好地“自我文档化”的方法:接下来,您希望以第二个
<div>
为目标,但不要按索引搜索,而是尝试使用元素的属性(如果适用),例如class
:最后,您希望以价格作为
<div>
的目标。因为“New”文本是在它自己的<div>
中,所以XPath的目标是第一个<div>
(“New”),而不是带有价格的<div>
。但是,如果“新”文本<div>
不存在,XPath就可以工作。你知道吗我们可以使用与上一步类似的方法,通过属性确定目标。这迫使XPath始终以
<div>
为目标,价格为:希望这有帮助!你知道吗
所以。。。说了这么多,如果你只对价格感兴趣,其他什么都不感兴趣,这可能也有用:)
你能试试这个代码吗:
它会打印出来
如果还需要其他细节,一定要告诉我
相关问题 更多 >
编程相关推荐