百度百科“网络爬虫”的词条

第一次接触正则表达式,和BeautifulSoup,第一印象就是复杂,必须要专门抽时间深入学习才行。

今天这个脚本初步应用他们的基本功能,爬取百度百科一个词条里面的其他词条链接。脚本没有采用之前的urllib.request而是直接用了request库来读取网页数据,据说这个更强大。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import requests
from bs4 import BeautifulSoup
import chardet
import re
import urllib.parse as up

url = 'http://baike.baidu.com/view/284853.htm'
agent = 'User-Agent'
agentvalue = 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.81 Safari/537.36'
headers = {agent:agentvalue}
proxy = {'http':'120.78.174.170:8080'}

response = requests.get(url = url, headers = headers, proxies = proxy)
code = chardet.detect(response.content)['encoding']#response.content是返回响应的二进制数据
response.encoding = code #response.encoding可以查询编码方式,也可以通过赋值对响应进行编码
html = response.text #response.text返回响应的文本数据
soup = BeautifulSoup(html, 'html.parser')
for tag in soup.find_all(href = re.compile('item')):
print(tag.text, '-->', ''.join(['http://baike.baidu.com', up.unquote(tag['href'])]))

上面第19行使用url解码把臃肿的连接地址解码成简短的包含有中文的地址,只要浏览器可以识别就没有关系。

http://baike.baidu.com/item//item/%E5%BC%80%E6%94%BE%E6%BA%90%E4%BB%A3%E7%A0%81

解码成:http://baike.baidu.com/item/开放源代码

参考:

Requests快速上手

python之urlencode(),quote()及unquote()