【问题标题】:How to prevent the use of urllib2 package in python 2.7?如何防止在 python 2.7 中使用 urllib2 包?
【发布时间】:2017-10-24 16:12:40
【问题描述】:

我正在尝试在下面做同样的事情,但不使用 urllib2 包。 我正在尝试网络抓取一个 URL(不完全是下面显示的那个)。 出于安全原因,必须有标题。

URL = 'https://www.google.com/search?q=test'
hdr = {'User-Agent': 'Mozilla/5.4'}
req = urllib2.Request(URL, headers=hdr)
pag = urllib2.urlopen(req)
soup = BeautifulSoup(pag, "lxml")
all_tables = soup.find_all('table')
right_table = soup.find_all('table')[1]

我曾尝试在堆栈溢出中查找此问题,但我只能使用 urllib2 找到解决方案。 我有理由不想使用 urllib2

有什么方法可以在不使用 urllib2 的情况下做到这一点? 我正在使用 python 2.7

谢谢。

【问题讨论】:

标签: python python-2.7 web-scraping urllib2 urllib


【解决方案1】:
import requests

URL = 'https://www.google.com/search?q=test'
hdr = {'User-Agent': 'Mozilla/5.4'}
req = requests.get(URL, headers=hdr)
soup = BeautifulSoup(req.content, "lxml")
all_tables = soup.find_all('table')
right_table = soup.find_all('table')[1]

【讨论】:

  • 我相信您可以为您的答案提供一些解释或cmets,使其变得更好。
猜你喜欢
  • 2020-05-25
  • 1970-01-01
  • 2019-09-29
  • 2016-06-20
  • 2012-12-05
  • 2014-01-12
  • 2017-11-04
  • 2023-03-17
  • 2019-01-31
相关资源
最近更新 更多