您使用的 xpath 特定于第一个清单的元素。为了能够访问每个列表的元素,您需要以一种可以帮助您访问每个列表的元素的方式使用 xpath:
import pandas as pd
from selenium import webdriver
我搜索了曼哈顿的待售房源并获得了以下网址
url = "https://www.zillow.com/homes/Manhattan,-New-York,-NY_rb/"
要求 selenium 在 Chrome 中打开上述链接
driver = webdriver.Chrome()
driver.get(url)
我将鼠标悬停在其中一个房屋清单上,然后单击“检查”。这打开了 HTML 代码并突出显示了我正在检查的项目。我注意到具有“list-card-info”类的元素包含我们需要的所有房子信息。因此,我们的策略是让每个房子都访问具有类“list-card-info”的元素。因此,使用以下代码,我将所有此类 HTML 块保存在 house_cards 变量中
house_cards = driver.find_elements_by_class_name("list-card-info")
house_cards 中有 40 个元素,即每个房子一个(每页列出 40 个房子)
我遍历这 40 个房子中的每一个,并提取我需要的信息。请注意,我现在使用的是特定于“list-card-info”元素中的元素的 xpath。我将此信息保存在熊猫数据报中。
address = []
price = []
bedrooms = []
baths = []
sq_ft = []
for house in house_cards:
address.append(house.find_element_by_class_name("list-card-addr").text)
price.append(house.find_element_by_class_name("list-card-price").text)
bedrooms.append(house.find_element_by_xpath('.//div[@class="list-card-heading"]/ul[@class="list-card-details"]/li[1]').text)
baths.append(house.find_element_by_xpath('.//div[@class="list-card-heading"]/ul[@class="list-card-details"]/li[2]').text)
sq_ft.append(house.find_element_by_xpath('.//div[@class="list-card-heading"]/ul[@class="list-card-details"]/li[3]').text)
driver.quit()
# print(address, price,bedrooms,baths, sq_ft)
Manahattan_listings = pd.DataFrame({"address":address,
"bedrooms": bedrooms,
"baths":baths,
"sq_ft":sq_ft,
"price":price},)
pandas dataframe output
现在,要从更多页面(即第 2 页、第 3 页等)中提取信息,您可以遍历网站页面,即不断修改您的 URL 并继续提取信息
快乐抓取!