以中国旅游网首页(http://www.cntour.cn/)为例,抓取中国旅游网首页首条信息(标题和链接)
源码页面:
使用 GET 方式抓取数据:
使用 Beautiful Soup 解析网页:
清洗和组织数据:(未得到下图的效果)
相关代码:
# http://c.biancheng.net/view/2011.html
#coding=utf-8
import requests #导入requests
from bs4 import BeautifulSoup
# 使用 GET 方式抓取数据
url = 'http://www.cntour.cn/'
strhtml = requests.get(url) #Get方式获取网页数据
# print(strhtml.text)
# 使用 Beautiful Soup 解析网页
strhtml=requests.get(url)
soup=BeautifulSoup(strhtml.text,'lxml')
data = soup.select('a')
print(data)
# 查找html中所有a标签
# titles = soup.find_all('a')
# print(titles)
#main > div > div.newListBox.clearfix > div.leftBox > div.newsList > ul > li:nth-child(1) > a
# 清洗和组织数据
# 要提取的数据是标题和链接,标题在<a>标签中,提取标签的正文用 get_text() 方法。
# 链接在<a>标签的 href 属性中,提取标签中的 href 属性用 get() 方法,在括号中指定要提取的属性数据,即 get('href')。
for item in data:
result={
'title':item.get_text(),
'link':item.get('href')
}
# print(result)
# 调用正则表达式时使用 re 库
# \d匹配数字
# +匹配前一个字符1次或多次
# import re
# for item in data:
# result={
# "title":item.get_text(),
# "link":item.get('href'),
# # 'ID':re.findall('\d+',item.get('href')) #正则表达式
# }
# print(result)
# open()是读写文件的函数,with语句会自动close()已打开文件
# with open(r"C:\Users\sky\Desktop\document.txt", "w",encoding='utf-8') as file: #打开/创建一个txt文件
# for title in titles: #遍历titles中的每个元素
# file.write(title.string+'\n') #向文件中写入title的字符串(即文章的标题),并换行
# file.write(title.get('href') + '\n\n') #向文件中写入文章的链接,并两次换行
结果: