nil*_*far 46 python beautifulsoup web-scraping urllib3
我想写一段代码,如下所示:
from bs4 import BeautifulSoup
import urllib2
url = 'http://www.thefamouspeople.com/singers.php'
html = urllib2.urlopen(url)
soup = BeautifulSoup(html)
Run Code Online (Sandbox Code Playgroud)
但我发现我现在必须安装urllib3
包.
此外,我找不到任何教程或示例来了解如何重写上面的代码,例如,urllib3
没有urlopen
.
请问任何解释或示例?!
P/S:我正在使用python 3.4.
sha*_*zow 47
urllib3是与urllib和urllib2不同的库.如果需要,它还有标准库中urllib的许多附加功能,例如重用连接.文档在这里:https://urllib3.readthedocs.org/
如果你想使用urllib3,你需要pip install urllib3
.一个基本示例如下所示:
from bs4 import BeautifulSoup
import urllib3
http = urllib3.PoolManager()
url = 'http://www.thefamouspeople.com/singers.php'
response = http.request('GET', url)
soup = BeautifulSoup(response.data)
Run Code Online (Sandbox Code Playgroud)
ale*_*cxe 32
您不必安装urllib3
.您可以选择任何符合您需求的HTTP请求制作库,并将响应提供给BeautifulSoup
.选择通常是requests
因为丰富的功能集和方便的API.您可以requests
通过pip install requests
在命令行中输入来安装.这是一个基本的例子:
from bs4 import BeautifulSoup
import requests
url = "url"
response = requests.get(url)
soup = BeautifulSoup(response.content, "html.parser")
Run Code Online (Sandbox Code Playgroud)
新的urllib3库在这里有一个不错的文档,
为了获得所需的结果,您应该遵循以下步骤:
Import urllib3
from bs4 import BeautifulSoup
url = 'http://www.thefamouspeople.com/singers.php'
http = urllib3.PoolManager()
response = http.request('GET', url)
soup = BeautifulSoup(response.data.decode('utf-8'))
Run Code Online (Sandbox Code Playgroud)
“解码utf-8”部分是可选的。当我尝试时没有它就可以工作,但是无论如何我都发布了该选项。
资料来源:用户指南