爬取https://www.aqistudy.cn/historydata/中的城市名称
通过xpath表达式解析网站中的城市名称,利用for循环获取全部城市名称,并将获取的城市名称放到列表中。
# 爬取https://www.aqistudy.cn/historydata/中的城市名称
import requests
from lxml import etree
if __name__ =='__main__':
url = 'https://www.aqistudy.cn/historydata/'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36'
}
response = requests.get(url=url,headers=headers)
page_text = response.text
#爬取热门城市
tree = etree.HTML(page_text)
li_list = tree.xpath('//div[@class="bottom"]/ul/li')
all_city_name=[]
for li in li_list:
hot_city_name = li.xpath('./a/text()')[0]
all_city_name.append(hot_city_name)
#爬取全部城市
ul_list = tree.xpath('//div[@class="bottom"]/ul/div[2]/li')
for ul in ul_list:
city_name = ul.xpath('./a/text()')[0]
all_city_name.append(city_name)
print(all_city_name,len(all_city_name))