这是我第一次使用Python和web抓取。一直在四处寻找,仍然无法得到我需要做的。在
下面是我通过Chrome使用过的元素的打印屏幕。在
我要做的是,我试着从选定的城市名称中获取公寓名称和地址。在
import requests
from bs4 import BeautifulSoup
#url = 'http://www.homestead.ca/apartments-for-rent/'
rootURL = 'http://www.homestead.ca'
response = requests.get(rootURL)
html = response.content
soup = BeautifulSoup(html,'lxml')
dropdown_list = soup.select(".primary .child-pages a")
#city_names=[dropdown_list_value.text for dropdown_list_value in dropdown_list]
#print (city_names)
cityLinks=[rootURL + dropdown_list_value['href'] for dropdown_list_value in dropdown_list]
for cityLinks_select in dropdown_list: #Looping each city from the Apartment drop down list
print ('Selecting city:',cityLinks_select.text)
cityResponse = requests.get(cityLinks)
cityHtml = cityResponse.content
citySoup = BeautifulSoup(cityHtml,'lxml')
community_list = soup.select(".extended-search .property-container a[h2 h3]")
get and print the apartment link
get and print the apartment name
get and print the address of the apartment
正如我所说,有些数据是动态创建的,如果我们看一下源代码本身,我们会看到:
我们能从源头得到的只有建筑名称、地址和电话号码:
^{pr2}$如果我们模仿ajax请求,我们可以获得json格式的所有数据:
现在我们得到的数据如下:
这会给你网址,卧室和几乎所有你想要的东西。列表中的每一个dict都是一个列表,您只需使用键来访问所需的数据,例如:
会给你:
联系人信息在
dct["contact"]
下,统计信息在=dct["statistics"]
下:这会给你:
你可以把所有这些放在一起得到你需要的东西。你可以调整参数,如果你在chrome工具或firebug中查看请求,实际上还有更多。在
相关问题 更多 >
编程相关推荐