【问题标题】:How to scrape a webpage using Beautiful Soup as if using Chrome?如何像使用 Chrome 一样使用 Beautiful Soup 抓取网页?
【发布时间】:2018-05-11 09:38:09
【问题描述】:

当我查看同一网页的源代码时,我在 google chrome (Inspect) 中获得了某些元素,但在 Internet Explorer 中却没有。

我假设 Beautiful Soup 在内部使用 Internet Explorer?其结果与 IE 更接近。

但是,当我使用 chrome 的 Inspect 功能时,我看到了源代码中未列出的某些元素。

有没有办法可以在 Python 中或使用 Beautiful Soup 进行模拟?

【问题讨论】:

  • 您是否尝试添加像 ie 或 chrome 这样的用户代理?
  • 不,我现在就试试这个。

标签: python web-scraping beautifulsoup


【解决方案1】:

您可以将您的用户代理更改为以下之一:

https://webscraping.com/blog/User-agents/

片段:更改用户代理会强制页面打开不同的内容(移动设备与 Chrome)

from bs4 import BeautifulSoup
import requests
#headers = {'User-Agent': 'Mozilla/5.0 (X11; U; Linux i686; en-US) AppleWebKit/534.3 (KHTML, like Gecko) Chrome/6.0.472.63 Safari/534.3'}
headers = {'User-Agent': 'Mozilla/5.0 (Linux; Android 5.1.1; SM-G928X Build/LMY47X) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.83 Mobile Safari/537.36'}
result = requests.get("http://derstandard.at", headers=headers)
c = result.content
print result.request.headers


print len(c)

注意:一些网站为user-agent spoofing 保护他们的自拍。因此,并非所有网站都会响应这些频繁的跳转。

【讨论】:

  • thx 似乎 requests 是我必须下载的另一个库?我收到“ImportError:没有名为请求的模块”
  • 是的,基本上是很方便的。因此,如果您想进行抓取,强烈建议安装它。 pip install requests 如果您使用的是 linux 发行版。
  • @JoanVenge 毫无疑问,requests 是 python 中最好的 http lib。让我们尽快使用它。
  • 这个库可以模拟 Chrome 的 Inspect 功能吗?
  • 做更复杂的事情你应该看看:pypi.python.org/pypi/fake-useragent
猜你喜欢
  • 2016-05-16
  • 1970-01-01
  • 2020-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-25
  • 1970-01-01
相关资源
最近更新 更多