以 “中国旅游网”为例
本次需要下载的第三方库:request , bs4 , lxml
一:使用 request 的 get 方式抓取数据
import requests
url = 'http://www.cntour.cn/' #中国旅游网网址
str = requests.get(url) #此时 str 为 url对象,代表整个网页
print(str.text) #用.text展示网页中的源码
运行结果:
二:使用 BeautifulSoup 解析网页
import requests
from bs4 import BeautifulSoup
url = 'http://www.cntour.cn/' #中国旅游网网址
str = requests.get(url) #此时 str 为 url对象,代表整个网页
soup = BeautifulSoup(str.text,'lxml') #使用BeautifulSoup解析网页,解析器为lxml
data = soup.select('#main > div > div.mtop.firstMod.clearfix > div.centerBox > ul.newsList > li > a') #使用soup.select引用路径
print(data) #展示data
soup.select 后的路径如何寻找?
(1)例如选择该标题,右键点击检查
(2)然后出现源码,右键对应的源码,选择 copy—copy seletor 即可复制路径
(3)该路径仅选中了第一条新闻路径,将 li 的:后面的部分删除,就能获取所有的该类型新闻
运行结果:
三:清洗和组织数据
需要使用的正则符号:
匹配数字 : \d
匹配前一个字符1次或多次: +
import requests
from bs4 import BeautifulSoup
import re
url = 'http://www.cntour.cn/' #中国旅游网网址
str = requests.get(url) #此时 str 为 url对象,代表整个网页
soup = BeautifulSoup(str.text,'lxml') #使用BeautifulSoup解析网页,解析器为lxml
data = soup.select('#main > div > div.mtop.firstMod.clearfix > div.centerBox > ul.newsList > li > a') #使用soup.select引用路径
for item in data:
result={
#把数据整理为字典类型
'title': item.get_text(), #用 get_text()方法提取标签的正文
'link': item.get('href'), #用 get('href')用法提取标签中的href属性
'ID': re.findall('\d+',item.get('href')) #用正则表达式在href中提取出ID
}
print(result)
运行结果: