让我们使用 URL https://www.google.cl/#q=stackoverflow举个例子。在搜索给出的第一个链接上使用 Chrome 开发者工具,我们会看到以下 html 代码:
现在,如果我运行这段代码:
from urllib.request import urlopen
from bs4 import BeautifulSoup
url = urlopen("https://www.google.cl/#q=stackoverflow")
soup = BeautifulSoup(url)
print(soup.prettify())
我找不到相同的元素。事实上,我不会从谷歌搜索给出的结果中找到任何链接。如果我使用 requests
模块,情况也是如此。为什么会发生这种情况?我可以采取一些措施来获得与从网络浏览器请求相同的结果吗?
最佳答案
由于 html 是动态生成的,可能是从现代单页 JavaScript 框架(如 Angular 或 React)(甚至只是纯 JavaScript)生成的,因此在解析 dom 之前,您需要使用 selenium 或 phantomjs 将浏览器实际驱动到该站点。
这是一些框架代码。
from selenium import webdriver
from bs4 import BeautifulSoup
driver = webdriver.Chrome()
driver.get("http://google.com")
html = driver.execute_script("return document.documentElement.innerHTML")
soup = BeautifulSoup(html)
这里是 selenium 文档,了解有关运行 selenium、配置等的更多信息:
http://selenium-python.readthedocs.io/
编辑:
在获取 html 之前,您可能需要添加一个 wait
,因为加载页面的某些元素可能需要一秒钟左右的时间。请参阅下面引用 python selenium 的显式等待文档:
http://selenium-python.readthedocs.io/waits.html
另一个导致复杂化的原因是页面的某些部分可能会被隐藏,直到用户交互之后。在这种情况下,您需要对 selenium 脚本进行编码,以便在获取 html 之前以某种方式与页面进行交互。
关于python - 为什么 python 和我的网络浏览器对同一链接显示不同的代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38578875/