需求:1、分析网页结构
2、分析请求包
1、使用Chrom的开发者模式,获取User-Agent,如:
2、获取信息的路径:
代码如下:
# -*- coding: utf-8 -*-
import tensorflow as tf
from urllib import request
from lxml import etree
url="https://sz.lianjia.com/zufang/"
head={
"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36"
}
#定义请求
Request=request.Request(url=url,headers=head)
#发起请求
response=request.urlopen(Request)
#返回结果
result=response.read().decode()
#print(result)
#进行数据过滤
html=etree.HTML(result)
house_list=html.xpath('//ul[@id="house-lst"]/li/div[@class="info-panel"]/h2/a')
for house in house_list:
print(house.attrib["title"])
house_list2=html.xpath('//ul[@id="house-lst"]/li/div[@class="info-panel"]')
for house in house_list2:
house_name=house.xpath('h2/a')[0].attrib["title"]
house_address=house.xpath('div[@class="col-1"]/div[@class="other"]/div[@class="con"]/a')[0].text
print("#####################")
print("%s : %s"%(house_name,house_address))
print("#####################")