上一章最后提到了requests模块,这一章讲用requests爬取网页
先说一下get方式爬取的基本流程,举个例子百度产品:
import requests
url = "https://www.baidu.com/more/"
resp = requests.get(url)
# html = resp.text
# print(html)
html = resp.content.decode("utf-8")
print(html)
可以看见我注释了两行代码,注释掉的这两行其实效果大部分时间是一样的。
还可以在get上携带参数,比如下面:
url = "https://search.sina.com.cn/?"
params = {
"q": "NBA",
"c": "news",
"from": "all",
"ie": "utf-8"
}
resp = requests.get(url, params=params)
print(resp.url)
# https://search.sina.com.cn/?q=NBA&c=news&from=all&ie=utf-8
print(resp.text)
params参数会自动拼接字符串
也可以携带参数和请求:
params = {"wd": "长城"}
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36',}
resp = requests.get("https://www.baidu.com/s?", params=params, headers=headers)
print(resp.url)
# https://www.baidu.com/s?wd=%E9%95%BF%E5%9F%8E
print(resp.text)
中文参数被百度自动加密了
通过一个爬取百度翻译数据来大致了解一下:
url = "https://fanyi.baidu.com/sug"
data = {"kw": "job"}
resp = requests.post(url, data=data)
jsonData = resp.json()
print(jsonData)
result = ""
for item in jsonData["data"]:
result += item["v"] + "\n"
print(result)
结果太长就不展示了
可以看到这里的参数使用的是data因为在post请求参数被封装在报文里面了。
当然也有携带请求头和参数的post请求,举一个有道词典的例子:
在 http://fanyi.youdao.com/ 这里输入python按f12后我们可以看见
i: python
from: AUTO
to: AUTO
smartresult: dict
client: fanyideskweb
salt: 15819485581857
sign: f13132ebd7283c29c0e85874f66658f0
ts: 1581948558185
bv: 901200199a98c590144a961dac532964
doctype: json
version: 2.1
keyfrom: fanyi.web
action: FY_BY_REALTlME
我们可以使用pycharm的正则替换使他变成字典
data = {
'i': 'python',
'from': 'AUTO',
'to': 'AUTO',
'smartresult': 'dict',
'client': 'fanyideskweb',
'salt': '15819485581857',
'sign': 'f13132ebd7283c29c0e85874f66658f0',
'ts': '1581948558185',
'bv': '901200199a98c590144a961dac532964',
'doctype': 'json',
'version': '2.1',
'keyfrom': 'fanyi.web',
'action': 'FY_BY_REALTlME',
}
headers = {
'Accept': 'application/json, text/javascript, */*; q=0.01',
'Accept-Encoding': 'gzip, deflate',
'Accept-Language': 'zh-CN,zh;q=0.9',
'Connection': 'keep-alive',
'Content-Length': str(len(data)),
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'Cookie': 'OUTFOX_SEARCH_USER_ID_NCOO=123919342.01547052; [email protected]; JSESSIONID=aaaL-p7mI1orBhRfszsbx; ___rl__test__cookies=1581930513153',
'Host': 'fanyi.youdao.com',
'Origin': 'http://fanyi.youdao.com',
'Referer': 'http://fanyi.youdao.com/',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.100 Safari/537.36',
'X-Requested-With': 'XMLHttpRequest',
}
url = 'http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule'
resp = requests.post(url, data=data, headers=headers)
jsonData = resp.json()
print(jsonData)
在这里的情况是需要写死需要翻译的内容,如果不写死,我们就需要找出相关参数的加密方式。