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

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

发请求

发请求,

  • 可以使用更底层的requests库(requests参考文档https://2.python-requests.org/en/master/)模拟浏览器发送请求

如:
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)

>>> type(r.text)

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'

(.*?)

',html_page_source,re.DOTALL) links = re.findall(r'.*?',html_page_source,re.DOTALL)
  • 针对性解析——将HTML source解析成结构化对象

    • BeautifulSoup可以将HTML source解析成树形结构对象。参见https://www.crummy.com/software/BeautifulSoup/bs4/doc/index.html

    • selenium也可以通过find_element_by_*方法定位页面元素

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则更有针对性,封装了一些查找定位元素的操作,用起来更简洁一些。具体用哪个,看个人习惯

你可能感兴趣的:(python爬虫基础 2020-01-25(未经允许,禁止转载))