【问题标题】:The html code I get from the requests module in Python is different than the source code of the same webpage I get from the browser我从 Python 中的 requests 模块获得的 html 代码与我从浏览器获得的同一网页的源代码不同
【发布时间】:2020-11-21 09:39:24
【问题描述】:

在 Python 中使用 requests.get() 方法时,我得到的响应对象产生的 html 代码与我从浏览器 (Chrome) 获得的源代码不同。这让我很难使用 BeautifulSoup 模块解析代码。

有什么解决办法吗?我有什么错误吗?

下面给出的是我的 python 脚本。我从 chrome 获得的网页源代码在 r 类中有一个 a id,该类有一个 href 链接。所以我想我会得到一个链接。但它一直返回一个空列表。

import requests,bs4,webbrowser
res=requests.get('https://www.google.com/search?q=wind+river')
soup=bs4.BeautifulSoup(res.text, 'lxml')
sel=soup.select('.r a')
sel[0].get('href')

【问题讨论】:

  • Google 将阻止您,否则他们将发送验证码
  • @bigbounty 为什么会这样?
  • 这就是他们设计网站的方式

标签: python html beautifulsoup python-requests html-parsing


【解决方案1】:

Google 从 JavaScript 加载,因此请求无法加载结果。

试试:

from selenium import webdriver
import bs4

import time
url = 'https://www.google.com/search?q=wind+river'
driver = webdriver.Firefox(executable_path='c:/program/geckodriver.exe')
driver.get(url)
time.sleep(3)
driver.page_source
soup= bs4.BeautifulSoup(driver.page_source, 'lxml')
driver.close()
sel=soup.select('.r a')
print(sel[0].get('href'))

打印:

https://www.imdb.com/title/tt5362988/

注意 selenium:您需要 seleniumgeckodriver 并且在此代码中 geckodriver 设置为从 c:/program/geckodriver.exe 导入

【讨论】:

  • 这只能用requests和beautifulsoup模块完成吗?我用来学习python的书只使用这些模块来解析google搜索结果。
  • @KrishnaJS Nope.. 这本书可能不是新发行的?
  • 顺便说一句,即使在解析雅虎搜索页面时,我得到的代码也与源代码不同
  • 本书讲解使用Python3.4。
  • 添加 headers = {'User-Agent': 'Mozilla/5.0'}res=requests.get(url, headers=headers) 以从 yahoo 中抓取一些内容
猜你喜欢
  • 2022-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-26
  • 2016-06-23
  • 1970-01-01
  • 2020-12-05
  • 1970-01-01
相关资源
最近更新 更多