抓取中国国旅页面

抓取中国国旅页面

# 使用Beautiful Soup解析网页
import re
import time
import requests
from bs4 import BeautifulSoup  # pip3 install Beautifulsoup4 从bs4库导入BeautifulSoup

# 抓取中国国旅页面
url = 'http://www.cntour.cn/'  # get方式,获取网页数据

# 增加代理
# proxies = {
#     "http": "http://12.2.2.20:3128"
# }

# strhtml = requests.get(url, proxies=proxies)
strhtml = requests.get(url)
time.sleep(1)  # 休眠2s
soup = BeautifulSoup(strhtml.text, 'lxml')  # 解析网页文档
# 获取元素标签
data = soup.select('#main > div > div.mtop.firstMod.clearfix > div.centerBox > ul.newsList > li > a')
# print(data)
# <a href="http://www.cntour.cn/news/13800/" target="_blank" title="政策加码提振市场 生活消费加速回暖">政策加码提振市场 生活消费加速回暖</a>
# for item in data:
#     result = {
#         '标题': item.get_text(), # 提取标签<a>的正文使用get_text()方法
#         '地址': item.get('href')  # 提取标签<a>的href属性使用get()方法
#     }
#     print(result)

# 使用正则,取出文章id(url里面的数字id)
# \d:匹配数字,  +:匹配前一个字符一次或者多次
for item in data:
    result = {
        '标题': item.get_text(),  # 提取标签<a>的正文使用get_text()方法
        '地址': item.get('href'),  # 提取标签<a>的href属性使用get()方法
        '文章id': re.findall('\d+', item.get('href'))  # re库的findall方法,第一个参数表示正则表达式,第二个参数表示提取的文本
    }
    print(result)
    # {'标题': '政策加码提振市场 生活消费加速回暖', '地址': 'http://www.cntour.cn/news/13800/', 'id': ['13800']}

运行结果:

{'标题': '政策加码提振市场 生活消费加速回暖', '地址': 'http://www.cntour.cn/news/13800/', '文章id': ['13800']}
{'标题': '国家23部门联合发文促文旅消费', '地址': 'http://www.cntour.cn/news/13795/', '文章id': ['13795']}
{'标题': '景区“重启”,准备好了吗', '地址': 'http://www.cntour.cn/news/13791/', '文章id': ['13791']}
{'标题': '美丽中国建设有了评估体系', '地址': 'http://www.cntour.cn/news/13789/', '文章id': ['13789']}
{'标题': '[文创行业线上发力]', '地址': 'http://www.cntour.cn/news/13802/', '文章id': ['13802']}
{'标题': '[“无接触商业”加速到来]', '地址': 'http://www.cntour.cn/news/13792/', '文章id': ['13792']}
{'标题': '[主动迎接旅游转型]', '地址': 'http://www.cntour.cn/news/13790/', '文章id': ['13790']}
{'标题': '[文旅魅力 “云”端绽放]', '地址': 'http://www.cntour.cn/news/13779/', '文章id': ['13779']}
{'标题': '[景点开放要安全有序]', '地址': 'http://www.cntour.cn/news/13768/', '文章id': ['13768']}
{'标题': '[图解:10年旅游让生活更]', '地址': 'http://www.cntour.cn/news/13747/', '文章id': ['13747']}
{'标题': '[发展旅游产业要有大格局]', '地址': 'http://www.cntour.cn/news/12718/', '文章id': ['12718']}
{'标题': '[科技改变旅游]', '地址': 'http://www.cntour.cn/news/12716/', '文章id': ['12716']}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值