我从 Python 中的 requests 模块获得的 html 代码与我从浏览器获得的同一网页的源代码不同

Posted

技术标签:

【中文标题】我从 Python 中的 requests 模块获得的 html 代码与我从浏览器获得的同一网页的源代码不同【英文标题】: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 【发布时间】: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 为什么会这样? 这就是他们设计网站的方式 【参考方案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:您需要 selenium 和 geckodriver 并且在此代码中 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 中抓取一些内容

以上是关于我从 Python 中的 requests 模块获得的 html 代码与我从浏览器获得的同一网页的源代码不同的主要内容,如果未能解决你的问题,请参考以下文章

你还不会Python网络爬虫中的requests模块使用《一》

使用 python-requests 模块更新 Session 中的 Cookie

Python3中的requests模块怎样用?

使用Python中的'requests'模块发出POST请求

Python中的requests模块注意事项

你还不会Python网络爬虫中的requests模块使用?《二》