Python爬取某旅游网站中的中国城市信息

分析

这是目标网址
可以发现它是通过点击下一页来翻页的,所以可以大概率判断它每一页的链接是有规律的,我们找出它的前两页的链接:

https://place.qyer.com/china/citylist-0-0-1/
https://place.qyer.com/china/citylist-0-0-2/

可以发现的确是有规律的,再找一个稍微后一点的页面看看:

https://place.qyer.com/china/citylist-0-0-169/

这下确定无疑了,可以看到,它有171个页面,链接中的数字也是从1开始一直到171,所以可以用一个for循环来提取每一页的内容。
接下来就是分析如何提取一个页中的内容了,我个人最拿手的是xpath,有些人使用的是BeautifulSoup也行。
可以在Chrome的开发者工具中明显看到每一个城市对应一个li标签,所以我先将所有的li标签提取出来,提取结果是一个列表,列表中的每一个对象也是Selector对象,也就是说列表中的每一个li标签还可以使用xpath方法提取该节点中的内容。
接下来就是写好要提取的内容对应的xpath语句了,可以使用Full copy Xpath或在xpath helper插件中自己写。

代码编写

下面是程序的完整代码:

import requests  # the library to initiate a request
from fake_useragent import UserAgent  # the library to make the request header
import parsel  # the library to parse HTML
import csv  # the library to writer csv file

def getdata(url):
    headers = {
        "user-Agent": UserAgent().chrome
    }
    response = requests.get(url=url, headers=headers)
    response.encoding = response.apparent_encoding

    selector = parsel.Selector(response.text)
    # extract all li tags
    lis = selector.xpath('//ul[@class="plcCitylist"]/li')

    for li in lis:
        city_names = li.xpath('./h3/a/text()').get()
        city_names = city_names.rstrip()
        number_people = li.xpath('./p[2]/text()').get()
        place_hot = li.xpath('./p[@class="pois"]/a/text()').getall()
        place_hot = [place.strip() for place in place_hot]
        place_hot = '、'.join(place_hot)
        place_url = li.xpath('./p[@class="pics"]/a/@href').get()
        img_url = li.xpath('./p[@class="pics"]/a/img/@src').get()
        print(city_names, number_people, place_url, img_url, place_hot, sep='|')

        with open('qiongyouDate.csv', mode='a', encoding='utf-8', newline='') as file_object:
            csv_write = csv.writer(file_object)
            csv_write.writerow([city_names, number_people, place_url, img_url, place_hot])

def main():
    for i in range(1, 172):
        url = "https://place.qyer.com/china/citylist-0-0-{}/".format(str(i))
        getdata(url)

if __name__ == '__main__':
    main()

运行结果

运行上面的代码,爬取到的数据会打印在控制台中,并且运行完成后会在程序目录中生成一个名为qingyouDate.csv的csv文件,可以使用WPS或Excel将这个文件打开。

下面是运行截图:
在这里插入图片描述

下面是生成的csv文件内容截屏:
在这里插入图片描述
爬取速度有一点慢。。。还请大家耐心等待

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值