爬虫--Get 和 Post 方式爬取数据

以中国旅游网首页(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')            #向文件中写入文章的链接,并两次换行

结果:

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值