Skip to main content
 首页 » 编程设计

python之正确的库用法 : requests w/bs4. BeautifulSoup

2025年05月04日10leader

我刚刚从使用 urllib2 作为我的 HTTP 访问库切换到使用 request 库。在 urllib 中,您使用 BeautifulSoup 使用 findAll(tag='element') 函数拉取 html 元素,我是继续以相同的方式使用 BeautifulSoup 还是请求具有函数这简化了这个过程?


使用 urllib2 拉标签


import urllib2 
from bs4 import BeautifulSoup as BS 
 
response = urllib2.urlopen('http://stackoverflow.com/') 
soup = BS(response) 
 
for a in soup.findAll('a'): 
    print a['href] 

使用请求拉标签


import response 
 
response = request.get('http://stackoverflow.com/') 
 
for a in response.findAll('a'): 
    print a['href] 

请您参考如下方法:

request只会让从 URL 获取数据变得更容易,尤其是在存在重定向等情况下。它不会为您解析 HTML 的主体,您仍然应该使用 BeautifulSoup 来解析 并将它的导入添加到您的第二个代码片段中,例如:

soup = BS(response.text)