案例一:解析出全國全部城市名稱
代碼以下:
import requests
from lxml import etree
if __name__ == "__main__":
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36'
}
url = 'https://www.aqistudy.cn/historydata/'
page_text = requests.get(url=url, headers=headers).text
tree = etree.HTML(page_text)
#解析到熱門城市和全部城市對應的a標籤
# //div[@class="bottom"]/ul/li/ 熱門城市a標籤的層級關係
# //div[@class="bottom"]/ul/div[2]/li/a 所有城市a標籤的層級關係
a_list = tree.xpath('//div[@class="bottom"]/ul/li/a | //div[@class="bottom"]/ul/div[2]/li/a')
all_city_names = []
for a in a_list:
city_name = a.xpath('./text()')[0]
all_city_names.append(city_name)
print(all_city_names,len(all_city_names))
運行效果:
案例二:爬取58二手房中的房源信息
代碼以下:
import requests
from lxml import etree
if __name__ == "__main__":
headers = {
'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36'
}
#爬取到頁面源碼數據
url = 'https://bj.58.com/ershoufang/'
page_text = requests.get(url=url,headers=headers).text
#數據解析
tree = etree.HTML(page_text)
#存儲的就是li標籤對象
li_list = tree.xpath('//ul[@class="house-list-wrap"]/li')
fp = open('58.txt','w',encoding='utf-8')
for li in li_list:
#局部解析
title = li.xpath('./div[2]/h2/a/text()')[0]
print(title)
fp.write(title+'\n')
運行效果: