中国大学MOOC上的北京理工大学开的一门《python》网络爬虫与信息提取这门课的学习记录。
基础代码
1 | import requests |
如何简单地理解Python中的if name==”main“:
其中 r.raise_for_status() )在方法内部判断 r.status_code 是否等于200,不需要增加额外的if语句,该语句便于利用try‐except进行异常处理,r.apparent_encoding 是从内容中分析出的响应内容编码方式(备选编码方式),r.encoding 是从HTTP header中猜测的响应内容编码方式。
在上面的例子中 r.apparent_encoding 是 utf-8,r.encoding 是 ISO-8859-1,如果没有 r.encoding = r.apparent_encoding 这行代码的话,返回的不是中文的百度首页。
https://2.python-requests.org/en/master/api/#requests.Response.text
r.text :Content of the response, in unicode.
If Response.encoding is None, encoding will be guessed using chardet.
The encoding of the response content is determined based solely on HTTP headers, following RFC 2616 to the letter. If you can take advantage of non-HTTP knowledge to make a better guess at the encoding, you should set r.encoding appropriately before accessing this property.
Robots协议
作用:网站告知网络爬虫哪些页面可以爬取,哪些不可以爬取
形式:京东的Robots协议
1 | User-agent: * |
1 | # 注释,*代表所有,/代表根目录 |
Requests实战
百度360搜索关键词提交
1 | import requests |
百度关键词接口:https://www.baidu.com/s?wd=keyword
网络图片的爬取和存储
文件操作上不熟悉…
1 | import requests |