摘要
爬取的目的网站是小猪短租
使用requests + cssselect模块
说明
分析:
1. 看到搜索框,选中某个地址比如北京,点击搜索小猪按钮,发现网页的地址变成http://bj.xiaozhu.com;再选中另一个地址如上海,再次之前的操作,发现地址变成http://sh.xiaozhu.com。那么可以发现,搜索哪个城市,就变成"http://" + 城市名字的拼音缩写 + ".xiaozhu.com"
2. 在城市页面比如http://bj.xiaozhu.com中,点击翻页,发现地址有规律地变成:
http://bj.xiaozhu.com/search-duanzufang-p1-0/
http://bj.xiaozhu.com/search-duanzufang-p2-0/
http://bj.xiaozhu.com/search-duanzufang-p3-0/
尝试第0页是否也这样,把http://bj.xiaozhu.com/search-duanzufang-p0-0/输入浏览器网址,发现页面和http://bj.xiaozhu.com一样
所以,翻页操作就是"http://bj.xiaozhu.com/search-duanzufang-p" + 页码 + "-0/"
3.通过1,2的分析,我们发现,可以直接跳过第一步搜索,直接使用如下地址进行相关操作:
"http://" + 城市名字缩写 + ".xiaozhu.com/search-duagzufang-p" + 页码 + "-0/"
这样,就可以对某个城市的某一页的租房信息进行获取
参考文章: 菜鸟学Python
基本流程:
- 确定搜索的城市和进行翻页的范围
- for pageNum in 范围:
-
2.1 通过requests请求"http://" + 城市名字缩写 + ".xiaozhu.com/search-duagzufang-p" + str(pageNum) + "-0/"
-
2.2 通过2.1获取的html页面内容获取页面的租房信息
-
2.3 输出租房信息
-
代码的实现
from lxml import etree
import requests
import time
def getHTMLText(url):
try:
headers = {"user-agent":"Mozilla/5.0"}
html = requests.get(url, headers=headers)
html.raise_for_status()
html.encoding = html.apparent_encoding
return html.text
except:
return ""
def getCityInfo(html):
'获取每一页的信息'
try:
selector = etree.HTML(html)
titles = selector.cssselect("#page_list > ul > li > div.result_btm_con.lodgeunitname > div > a > span")
rentInfos = selector.cssselect("#page_list > ul > li > div.result_btm_con.lodgeunitname > div > em")
dict = {"titles": titles, "rentInfos": rentInfos}
return dict
except:
return ""
def searchCity(cityName, pages):
'获取城市的信息,翻页范围是[start, end)'
for pageNum in range(int(pages["start"]), int(pages["end"])):
print("page" + str(pageNum) + "的信息:")
url = "http://" + cityName + ".xiaozhu.com/search-duanzufang-p" + str(pageNum) + "-0/"
try:
html = getHTMLText(url)
dict = getCityInfo(html)
titles = dict["titles"]
rentInfos = dict["rentInfos"]
length = len(rentInfos)
# 输出信息
for each in range(length):
print(titles[each].text)
print(rentInfos[each].text)
time.sleep(60)
except:
continue
def main():
pages = {"start":0,"end":2}
searchCity("bj", pages)
if __name__ == '__main__':
main()
网友评论