Python3爬虫开发 -- 请求库

请求库用来发送 http 请求,获取目标页面。

urllib

urllib 是 Python3 内置的 HTTP 请求库。

GET 请求:

import urllib.request as request

if __name__ == "__main__":
    try:
        resp = request.urlopen(url="http://www.baidu.com")
    except Exception as e:
        print(str(e))
    else:
        print(type(resp))
        print(resp.info())
        if resp.readable:
            data = resp.read()
            print(type(data))
            print("%s" % data.decode("utf-8"))
        resp.close()
    finally:
        None

POST 请求,带有 data:

pagesize=1
result = ''
url = 'http://irm.cninfo.com.cn/ircs/index/search'
data = f'pageNo=0&pageSize={pagesize}&searchTypes=1%2C11%2C&keyWord=&market=&industry=&stockCode='
try:
    resp = request.urlopen(url=url, data=bytes(data,encoding="utf8"))
except Exception as e:
   print(str(e))
else:
    if resp.readable:
        result = json.loads(resp.read())
    resp.close()
finally:
   return result

Post 请求的时候,data 需要是 bytes 数组,不能是字符串:

POST data should be bytes, an iterable of bytes, or a file object. It cannot be of type str.

Requests

Requests 是一个发送 http 请求的 python 库,英文文档,中文文档:

pip3 install requests

Selenium

Selenium 是一个用于 Web 自动化测试的浏览器,能够用代码控制浏览器内操作的特性使 Selenium 具有更广阔的应用空间,英文文档、中文文档:

pip3 install selenium

Chrome Driver

Chrome Driver 和 Gecko Driver 是配合 Selenium 使用的,分别用来驱动 Chrome 浏览器和 Firefox 浏览器,安装方法见:chromedriver 和 geckodriver 。

Phantomjs

Phantomjs 是无界面的 WebKit 浏览器,无界面运行效率高,需要 下载安装 。可以被 Selenium 驱动,如下:

from selenium import webdriver
browser = webdriver.PhantomJS()
browser.get('https://www.baidu.com')
print(browser.current_url)

aiohttp

aiohttp 是一个异步发送 http 请求的 python 库,英文文档,采用异步机制,效率大大提高。

pip3 install aiohttp