python爬虫一般格式

写在前面:建议安装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网络爬虫从入门到实践》机械工业出版社

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值
>