使用 xpath 爬取当前页面所有城市名称

from lxml import etree
import requests

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/"
                      "85.0.4183.83 Safari/537.36"
    }

    response = requests.get(url=url, headers=headers)
    response.encoding = response.apparent_encoding
    page_text = response.text

    tree = etree.HTML(page_text)
    all_city_names = []
    a_list = tree.xpath("//div[@class='bottom']/ul/li/a | //div[@class='bottom']/ul/div[2]/li/a")
    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))

你可能感兴趣的:(Spider_Practise)