写在前面:建议安装BeautifulSoup模块,写爬虫可以节省不少时间。一般出错,参考终端给出的建议。
pip3 install bs4 -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com
伴随bs4安装的还有 lxml 模块
pip3 install lxml -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com
需要了解

图片来源:https://blog.csdn.net/weixin_42170439/article/details/90445043
python正则表达式:https://www.cnblogs.com/cq146637/p/8072540.html
主要了解re.findall函数的使用。
简单示例:

一般爬虫的格式如下:
import re
import time
import random
import requests
from bs4 import BeautifulSoup #页面解析模块
url="https://blog.csdn.net/"
params={'key1':'value1','key2':'value2'} #相当于https://blog.csdn.net?key1=value1&key2=value2
headers={'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36'}#User-Agent 使爬虫能够伪装成浏览器访问
r=requests.get(url,headers=headers,params=params,timeout=1); #设置链接、请求头、参数、超时
bsObj=BeautifulSoup(r.text,'html.parser')#转化为bs对象
list=bsObj.findAll('div', class_='title')#查找返回页面中标签为div,属性中class为title的标签
with open(r'd:\Temp\test.txt','w') as f: #将想要抓取的数据保存到文件中
for i in list: #一般用到bs对象的属性有.text,.(tag),.parent
print(i.find('h2').text.replace(' ','').replace('\n',''))#也可以是print(i.h2.text.replace(' ','').replace('\n',''))
f.write(i.find('h2').text.replace(' ','').replace('\n','')+'\n')
f.close()
建议参考书籍:
《python网络数据采集》人民邮电出版社
《python网络爬虫从入门到实践》机械工业出版社
3743

被折叠的 条评论
为什么被折叠?



