Python 爬虫常用代码
web基础:
Request核心代码:
POST相关:
BeautifulSoup:
Response Headers中的数据为浏览器向网站所传送的内容,包括浏览器的信息及cookies等。
status:200 正常 418 被发现时爬虫orz
(418时 需要进行包装(User-Agent详见后文))
在python3中 urllib 已经与 urllib2库整合,import urllib即可
import urllib.request
response = urllib.request.urlopen("http://www.baidu.com")
print(response.read().decode("utf-8"))
decode 可将其解码为便于浏览的文本。
常用post的测试网站:
httpbin.org
post 一些data的测试(使用bytes转为二进制文件)(模拟用户真实登录(cookies))
import urllib.request,urllib.parse
if __name__ == '__main__':
data = bytes(urllib.parse.urlencode({"hello":"world"}),encoding="utf-8")
response = urllib.request.urlopen("http://httpbin.org/post",data = data)
print(response.read().decode("utf-8"))
记得使用try...except urllib.error.URLError: 来实现超时的错误处理(常用)
data = bytes(urllib.parse.urlencode({"hello": "world"}), encoding="utf-8")
try:
req = urllib.request.Request("http://douban.com", data=data, headers=headers, method="POST")
response = urllib.request.urlopen(req)
print(response.read().decode("utf-8"))
except urllib.error.URLError as e:
if hasattr(e,"code"):
print(e.code)
if hasattr(e,"reason"):
print(e.reason)
反418操作:(亦是request 和 response结合使用的示例,用request获取 用urlopen打开request实例)
headers = { #模拟浏览器头部信息 向豆瓣服务器发送消息
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36" #from your browser
}
data = bytes(urllib.parse.urlencode({"hello":"world"}),encoding="utf-8")
req = urllib.request.Request("http://douban.com",data = data,headers = headers, method = "POST")
response = urllib.request.urlopen(req)
print(response.read().decode("utf-8"))
作用:将复杂的HTML文档转换成一个复杂的树形结构,每个节点都是Python对象, 所有对象可归纳为4种
(强大的 搜索html标签及内容的工具,免于繁重的find工作)
--Tag 标签
--NavigableString
--BeautifulSoup
--Comment
基础示例:
from bs4 import BeautifulSoup
file = open("baidu.html","rb")
html = file.read()
bs = BeautifulSoup(html,"html.parser")
print(bs.a)# get tag
print(bs.title.string) # get string inside tag
print(bs.a.attrs) # get attrs inside tag
常用搜索函数:
bs.find_all("a") # 完全匹配
bs.find_all(re.compile("a")) # 正则匹配
bs.find_all(id = "head") # 寻找id为head的标签
# 方法搜索: 传入一个函数,根据函数的要求来搜索
def rules():
return tag.has_attr("name")
bs.find_all(rules)
tlist = bs.select('title') # 通过标签来查找
tlist = bs.select('.mnav') # 通过类名来查找(# id)
tlist = bs.select('head > title') # 查找子标签
tlist = bs.select('.manv ~ .bri') # 查找兄弟标签
# 获取该文本的方法
print(tlist[0].get_text())