零零散散学习python也有一个多月,照着慕课视频的学习例子,写一个爬虫怎么都无法运行,于是转变方法,直接搜索网上的例子,然后参考来写。
这次想爬的是喷嚏图卦的每期标题,图卦列表网址:http://www.dapenti.com/blog/blog.asp?name=xilei&subjectid=70&page=1
源代码看出a标签里就是每期图卦标题,可以直接提取出来。
于是搜索“python 抓取多面数据”、“python 获取标签间文本内容”、“Python 写入数据到txt”,找到现成的代码组合,可以成功爬取。但之后因为中文字符问题“'gbk' codec can't encode character 'u2022' ”卡了一下,马上搜索成功解决。代码如下:
from bs4 import BeautifulSoup
import requests
for i in range(80): #直接跳到最后一页,可得总页面为80
html = 'http://www.dapenti.com/blog/blog.asp?name=xilei&subjectid=70&page={page}'.format(page=i)
r = requests.get(html, timeout = 30)
r.raise_for_status()
r.encoding = 'gbk'
soup = BeautifulSoup(r.text, 'html.parser')
for j in range(50): #每页图卦标题50条
a_lists = soup.select('a') #获取所有的a标签
a_value = a_lists[j].string
txt=str(a_value)
with open('pt.txt','a',encoding='utf-8') as file_handle: # .txt可以不自己新建,代码会自动新建
file_handle.write(txt) # 写入
file_handle.write('n')
#相关搜索的学习页面
#https://jingyan.baidu.com/article/fc07f9899470ec12ffe519de.html 怎样用python的beautifulsoup抓取多页数据
#https://blog.csdn.net/zhangju414/article/details/102639606 beautifulsoup怎样获取标签间文本内容
#https://blog.csdn.net/weixin_43451928/article/details/95628168 Python写入数据到txt文本中
#https://blog.csdn.net/u013155359/article/details/81566807 (已解决)'gbk'之外字符问题无法写入文件
爬取输出的txt文件如下,下拉可以得知图卦大概是在2010年3月开始每天更新,到现在十年了,十年如一日都在更新,感谢图卦作者。
![d0e93731859ac4adb6431ff897fc3e44.png](https://i-blog.csdnimg.cn/blog_migrate/f5a72e629c1669a5566243968f657a87.jpeg)