使xpath更具选择性?[网页抓取]

2024-09-27 22:38:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图打印出一些住房价格,但在使用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选择器选择数字而不是新的?你知道吗


Tags: fromdiv密码numberdriverselenium价格find
3条回答

您可以这样写,而无需加载图像,这可以提高您的抓取速度

from selenium import webdriver
# Unloaded image
chrome_opt = webdriver.ChromeOptions()
prefs = {"profile.managed_default_content_settings.images": 2}
chrome_opt.add_experimental_option("prefs", prefs)
driver = webdriver.Chrome(chrome_options=chrome_opt,executable_path="my/path/here")
driver.get("https://www.realtor.com/realestateandhomes-search/Bladen-County_NC/sby-6/pg-1?pgsz=10")
for house_number in range(1,11):
    try:
        price = driver.find_element_by_xpath('//*[@id="{}"]/div[2]/div[@class="srp-item-price"]'.format(house_number))
        print(price.text)
    except:
        print('couldnt find')

你走对了路,你只是做了一个太脆弱的XPath。我会尽量使它更详细一点,而不依赖于索引和通配符。你知道吗


下面是XPath(我使用id="1"作为示例):

//*[@id="1"]/div[2]/div[1]

下面是HTML(为了简洁起见,删除了一些属性/元素):

<li id="1">
    <div></div>
    <div class="srp-item-body">
        <div>New</div><!  this is optional!  >
        <div class="srp-item-price">$100,000</div>
    </div>
</li>

首先,将*通配符替换为您希望包含id="1"的元素。这只是一种帮助XPath更好地“自我文档化”的方法:

//li[@id="1"]/div[2]/div[1]

接下来,您希望以第二个<div>为目标,但不要按索引搜索,而是尝试使用元素的属性(如果适用),例如class

//li[@id="1"]/div[@class="srp-item-body"]/div[1]

最后,您希望以价格作为<div>的目标。因为“New”文本是在它自己的<div>中,所以XPath的目标是第一个<div>(“New”),而不是带有价格的<div>。但是,如果“新”文本<div>不存在,XPath就可以工作。你知道吗

我们可以使用与上一步类似的方法,通过属性确定目标。这迫使XPath始终以<div>为目标,价格为:

//li[@id="1"]/div[@class="srp-item-body"]/div[@class="srp-item-price"]

希望这有帮助!你知道吗


所以。。。说了这么多,如果你只对价格感兴趣,其他什么都不感兴趣,这可能也有用:)

for price in driver.find_elements_by_class_name('srp-item-price'):
    print(price.text)

你能试试这个代码吗:

from selenium import webdriver
driver = webdriver.Chrome()
driver.maximize_window()
driver.get("https://www.realtor.com/realestateandhomes-search/Bladen-County_NC/sby-6/pg-1?pgsz=10")

prices=driver.find_elements_by_xpath('//*[@class="data-price-display"]')

for price in prices:
    print(price.text)

它会打印出来

$39,900
$86,500
$39,500
$40,000
$179,000
$31,000
$104,900
$94,900
$54,900
$19,900

如果还需要其他细节,一定要告诉我

相关问题 更多 >

    热门问题