python爬虫基础 2020-01-25(未经允许,禁止转载)

爬虫本质上就是模仿浏览器,没有其他
因此,爬虫仅仅需要做好浏览器端的两件事——【发请求解析响应

发请求

发请求,

如:
res = requests.get(url, params=payload, headers=headers),
res = requests.post(url, data=payload, headers=headers,verify=False)
这里payload都是dict

>>> import requests
>>> r = requests.get('https://api.github.com/events')
>>> type(r.content)
<class 'bytes'>
>>> type(r.text)
<class 'str'>

content是响应的二进制码,而text是基于对应的编码解析content得到的str。对于使用何种编码解析content,以下是官方文档说明:

Requests will automatically decode content from the server. Most unicode charsets are seamlessly decoded.

When you make a request, Requests makes educated guesses about the encoding of the response based on the HTTP headers. The text encoding guessed by Requests is used when you access r.text. You can find out what encoding Requests is using, and change it, using the r.encoding property:

>>> r.encoding
'utf-8'
>>> r.encoding = 'ISO-8859-1'

If you change the encoding, Requests will use the new value of r.encoding whenever you call r.text.

关于requests的其他具体用法,参见https://2.python-requests.org/en/master/

  • 或者使用高一点的selenium库驱动真实浏览器发送请求

from selenium import webdriver

browser = webdriver.Chrome(‘driver_path’)

browser.get(url)
# 这里的page_source是被浏览器解析完毕之后的web source code
print(browser.page_source)
browser.close() 

WebDriver offers a number of ways to find elements using one of the find_element_by_* methods.

更多用法可以参考selenium官方文档https://selenium-python.readthedocs.io/index.html

解析请求

解析请求,就是提取服务器返回的响应中那些被需要的信息

  • 简单实用型——使用正则表达式re库,提取text字符串中的目标信息

# 默认情况下,正则表达式中的dot(.)表示所有除了换行的字符,加上re.DOTALL参数后,能真正匹配所有字符,包括换行符\n
titles = re.findall(r'<p class="name"><a href.*?>(.*?)</a></p>',html_page_source,re.DOTALL)
links = re.findall(r'<img data-src="(.*?)" alt=".*?".*?/>',html_page_source,re.DOTALL)
from selenium import webdriver

browser = webdriver.Chrome(‘driver_path’)

browser.get(url)
browser.find_element_by_id("kw").send_keys("python")
browser.find_element_by_id("su").submit()

小结

  • 1.selenium一个库可以承担发送请求解析响应的全程任务。从实现爬虫功能的角度看,这一个库就够用了。另外,这个库比较高层,它驱动了浏览器,每一个动作都对用户可见,不过也因此效率受到一定影响
  • 2.使用re提取response目标信息更加通用,只要会正则表达式就能干活;而BeautifulSoup则更有针对性,封装了一些查找定位元素的操作,用起来更简洁一些。具体用哪个,看个人习惯
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容