抓取中国国旅页面
# 使用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']}