Skip to content

爬虫

BeatifulSoup4

bs = BeautifulSoup(html.read(), 'html.parser')

  • html.parser python自带解析器

  • lxml 需单独安装,依赖于第三方的C语言库pip3 install lxml 优点是能处理杂乱或者包含错误的标签,如未闭合的html标签,缺失的head或body标签。处理速度快

  • html5lib 能忍受更糟糕的语法,但处理速度比前两个都慢

处理异常

html = urlopen('http://www.pythonscraping.com/pages/warandpeace.html')

这个代码存在两种错误

  • 网页在服务器上不存在(或者获取页面的时候出现错误)
  • 服务器不存在

第一种情况返回HTTP错误,HTTP 错误可能是“404 Page Not Found”“500 Internal Server Error”等。可以下面的方式处理异常

try:
 html = urlopen('http://www.pythonscraping.com/pages/page1.html')
except HTTPError as e:
 print(e)
 # 返回空值,中断程序,或者执行另一个方案
else:
 # 程序继续。注意:如果你已经在上面异常捕捉那一段代码里返回或中断(break),
 # 那么就不需要使用else语句了,这段代码也不会执行

第二种情况,服务器不存则无法返回http错误代码,urlopen此时会抛出URLerror,可以增加检查代码except HTTPError as e:

print(bs.nonExistentTag)这段代码返回一个None对象,我们需要检查和处理这个对象,如果不处理直接调用其子标签print(bs.nonExistentTag.someTag)此时会返回一个AttributeError异常。

bs4常用函数

bsBeautifulSoup

find(tag, attributes, recursive, text, keywords) 返回

find_all(tag, attributes, recursive, text, limit, keywords)
返回python列表包含所有符合条件的标签 例如bs.find_all('span', {'class': 'red'})返回所有class为red的span标签

get_text() 会清除你正在处理的 HTML 文档中的所有标签,然后返回一个只包含文字的 Unicode 字符串。

a = '<span>this is span</span>'
BeautifulSoup(a,'html.parser').get_text()
# 返回this is span

b站番剧索引页api

https://api.bilibili.com/pgc/season/index/result?st=1&order=3&season_version=-1&spoken_language_type=-1&area=-1&is_finish=-1&copyright=-1&season_status=-1&season_month=-1&year=-1&style_id=-1&sort=0&page=1&season_type=1&pagesize=20&type=1

关于cookies
从网页使用document.cookies得到的格式形如VIP_CONTENT_REMIND=1; VIP_DEFINITION_GUIDE=1,可用下面的代码解析cookies为字典对象

cookies = {}
with open('bili_cookies') as c:
    c_text = c.read().strip(';')  #读取文本内容
    #手动分割添加cookie
    for item in c_text.split(';'):
        name,value=item.strip().split('=',1)  #用=号分割,分割1次
        cookies[name]=value  #为字典cookies添加内容

requests快速上手
根据url的协议匹配proxies中对应协议的代理ip,实测打开clash后不加参数proxies也是可行的

import requests
url = ''
# 代理对应url的协议
proxies = {
    'http':'http://127.0.0.1:7890',
    'https':'http://127.0.0.1:7890'
}

r = requests.get(url,proxies=proxies) # return response object
r.text # 解码内容部分
r.encoding # 设置编码格式,例如utf-8,GBK等
r.content # 二进制的内容部分
r.status_code # 返回http状态码