【问题标题】:Why is the html in view-source different from what I see in the terminal when I call prettify()?为什么当我调用 prettify() 时,view-source 中的 html 与我在终端中看到的不同?
【发布时间】:2018-05-05 04:22:25
【问题描述】:

我决定查看一个网站的源代码,并选择了一个“扩展”类(I found it using view-source,prettify() 显示不同的代码)。我想用这段代码打印出它的所有内容:

import requests
from bs4 import BeautifulSoup

page = requests.get("https://www.quora.com/How-can-I-write-a-bot-using-Python")
soup = BeautifulSoup(page.content, 'html.parser')
print soup.find_all(class_='expanded')

但它只是打印出来:

[]

请帮我找出问题所在。

我已经看到this thread 并尝试按照答案所说的进行操作,但这对我没有帮助,因为此错误出现在终端中:

bs4.FeatureNotFound:找不到具有您请求的功能的树生成器:lxml。需要安装解析器库吗?

【问题讨论】:

  • 使用page.text 而不是page.content

标签: python beautifulsoup


【解决方案1】:

我查看了有问题的网站,唯一类似的类实际上名为ui_qtext_expanded

当您使用 findAll / find_all 时,您必须对其进行迭代以返回每个项目,因为它是使用 .text 的项目列表。如果您想要文本而不是实际的 HTML..

import requests
from bs4 import BeautifulSoup

page = requests.get("https://www.quora.com/How-can-I-write-a-bot-using-Python")
soup = BeautifulSoup(page.content, 'html.parser')
res = soup.find_all(class_='ui_qtext_expanded')
for i in res:
    print i.text

链接输出的开头是

A combination of mechanize, Requests and BeautifulSoup works pretty good for the basic stuff.Learn about mechanize here.Mechanize is sufficient for basic form filling, form submission and that sort of stuff, but for real browser emulation (like dealing with Javascript rendered HTML) you should look into selenium.

【讨论】:

  • 所以你是说当我想对来自网站的实际信息做一些事情时,视图源是不可靠的,例如勾选框?我需要将整个 html 打印到终端才能查看吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-27
  • 1970-01-01
  • 1970-01-01
  • 2023-03-16
  • 1970-01-01
  • 2013-10-20
相关资源
最近更新 更多