【问题标题】:Python traceback error when using BeautifulSoup使用 BeautifulSoup 时出现 Python 回溯错误
【发布时间】:2018-06-23 03:38:48
【问题描述】:

我知道这个问题的变体已被问过一百次,但我无法找到适合我情况的答案。

我是 python 新手,我正在尝试使用以下代码:

import urllib
import requests

from bs4 import BeautifulSoup

theurl = "https://twitter.com"
thepage = requests.get(theurl)
soup = BeautifulSoup(thepage, "html.parser")

print(soup.title)

因此我收到以下错误:

Traceback (most recent call last):   File
"/Users/username/PycharmProjects/WebScraper2.0/web.py", line 8, in
 <module>
     soup = BeautifulSoup(thepage, "html.parser")   File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/bs4/__init__.py",
 line 192, in __init__
     elif len(markup) <= 256 and ( TypeError: object of type 'Response' has no len()

这里有什么问题?我仍在尝试熟悉错误代码,据我所知,这个错误代码似乎很笼统。有人愿意帮助我并解释问题所在吗?从我看到的例子来看,这应该可以工作......我错过了什么?

【问题讨论】:

标签: python beautifulsoup python-requests


【解决方案1】:

您需要在您抓取的 URL 文本周围调用 BeautifulSoup(),而不是实际请求:

soup = BeautifulSoup(thepage.text, "html.parser")

【讨论】:

  • 成功了!谢谢!它不会让我接受答案,但一旦接受,我就会给你功劳。
  • thepage.content 也应该可以工作,但不确定每个的详细区别。
【解决方案2】:

试试下面的 sn-p :

import requests
from bs4 import BeautifulSoup

r=requests.get("https://twitter.com")
c=r.content

soup=BeautifulSoup(c,"html.parser")

print(soup.title)

【讨论】:

  • 上面的 sn-p 是一个工作演示,它给出了预期的结果。我找不到对解决方案投反对票的原因。
猜你喜欢
  • 2017-04-13
  • 1970-01-01
  • 2015-03-25
  • 1970-01-01
  • 2018-02-12
  • 1970-01-01
  • 1970-01-01
  • 2020-06-19
  • 2017-08-31
相关资源
最近更新 更多