【发布时间】:2023-03-27 16:08:01
【问题描述】:
我正在尝试使用 BeautifulSoup 从网站上抓取房地产列表的 MLS 编号、价格和地址。
import requests
from bs4 import BeautifulSoup
# string url
str_url = 'https://www.utahrealestate.com/search/map.search'
# get response
response = requests.get(str_url)
# get html
soup = BeautifulSoup(response.text, 'html.parser')
# get the number of listings and assign it to int_n_pages (I cant get this to work; it returns NoneType)
int_n_pages = soup.find('li', {'class': 'view-results'})
# split and get n pages (this does not work because the previous line does not work)
int_n_pages = int(int_n_pages.split(' ')[2])
接下来,我的计划是遍历所有页面并从每个列表中提取信息。
类似...
# empty list
list_dict_cards = []
# iterate through pages
for int_page in range(1, int_n_pages+1):
# get url
str_url = f'https://www.utahrealestate.com/search/map.search/page/{int_page}/vtype/map'
# get response
response = requests.get(str_url)
# get html
soup = BeautifulSoup(response.text, 'html.parser')
# get property cards
property_cards = soup.find_all(class_='property___card')
# iterate through property cards
for card in property_cards:
# empty dict
dict_card = {}
# get mls number
int_mls = card.find(class_='mls___number').text.split(' ')[1]
# put into dict_card
dict_card['mls'] = int_mls
# I would get other info here as well and put into dict_card
# append dict_card to list_cards
list_dict_cards.append(dict.card)
# make df
df_cards = pd.DataFrame(list_dict_cards)
# save
df_cards.to_csv('./output/df_dict_cards.csv', index=False)
我很确定该网站正试图阻止以编程方式访问它显示的大部分信息。
这附近有什么/有什么地方吗?
【问题讨论】:
-
页面可能部分是使用 Javascript 生成的,而 bs4 无法执行。您要么需要使用 Selenium 之类的工具来正确呈现页面并从中提取数据,要么使用浏览器的开发人员工具研究页面的工作方式。
-
您是否真正查看过此页面返回的 HTML?我并不是说要查看 DOM 位。我的意思是原始 HTML。这就是
requests.get返回的内容。你要找的东西不在那里。它们是在运行时使用 Javascript 构建的。您将需要使用 Selenium 来获得它。是的,他们当然是在试图阻止人们窃取他们受版权保护的信息。 -
那么您的问题到底是什么?
标签: python web-scraping beautifulsoup