python爬虫学习笔记二(3):编写第一个简单的爬虫

参考书目 《python网络爬虫从入门到实践》唐松

2.4 编写第一个简单的爬虫

2.4.1 第一步:获取页面

import requests
url = "http://www.santostang.com/"
headers = {'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3766.400 QQBrowser/10.6.4163.400'}

r = requests.get(url, headers = headers)
print(r.text)#获取网页内容代码

2.4.1 第二步:提取需要的数据

import requests
from bs4 import BeautifulSoup

url = "http://www.santostang.com/"
headers = {'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3766.400 QQBrowser/10.6.4163.400'}

r = requests.get(url, headers = headers)
soup = BeautifulSoup(r.text, "html.parser")#使用beautifulsoup解析

#单击“检查”命令,找到第一篇文章标题,定位到class=post-title的h1元素,提取a以及里面的字符串,再用strip()去除左右空格
title = soup.find("h1", class_="post-title").a.text.strip()
print(title)

问题1: class后面为什么有"_"下划线
问题2: ".a.text"为什么没有把该章节的链接一起提取出来
第一篇文章标题的代码

2.4.1 第三步:存储数据

import requests
from bs4 import BeautifulSoup

url = "http://www.santostang.com/"
headers = {'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3766.400 QQBrowser/10.6.4163.400'}
r = requests.get(url, headers = headers)

soup = BeautifulSoup(r.text, "html.parser")#使用beautifulsoup解析
title = soup.find("h1", class_="post-title").a.text.strip()
print(title)

#打开一个空白的txt文件,使用f.write写入刚刚的字符串title
with open('title_test.txt', "a+") as f:
  f.write(title)
 #txt文件地址要和python文件放在同一个文件夹

文件内容

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值