【问题标题】:Requests/BeautifulSoup throwing error parsing given idRequests/BeautifulSoup 抛出错误解析给定的 id
【发布时间】:2016-02-13 18:41:27
【问题描述】:

我正在尝试解析:html 中的 id=qualifications。

我遵循了beautifulsoup 文档,并要求提供文档。

我的代码:

import requests
from bs4 import BeautifulSoup

def get_content(url):
    if type(url) != str:
        print('You need to included a string')
        exit()
    else:
        req  = requests.get(url)
        soup = BeautifulSoup(req, 'html.parser')
        qualifications = soup.find(id="qualifications")
        print('Qualifications:\n{}'.format(qualifications))

当我像这样运行它时:

get_content('http://www.somesite.com')

它抛出一个错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "parse.py", line 10, in get_content
    soup = BeautifulSoup(req, 'html.parser')
  File "python3.5/site-packages/bs4/__init__.py", line 176, in __init__
    elif len(markup) <= 256:
TypeError: object of type 'Response' has no len()

我怎样才能做到这一点?看起来错误可能是生成的请求的大小大于 256?

【问题讨论】:

  • 您需要包含该回溯的 rest。我们不知道实际引发了什么错误。
  • 啊,BeautifulSoup 不接受 requests 响应对象,不。

标签: python python-3.x beautifulsoup python-requests


【解决方案1】:

您传递的是 响应对象,而不是实际内容。你需要传入req.content

soup = BeautifulSoup(req.content, 'html.parser')

您可能希望传递服务器提供的任何编码信息:

encoding = req.encoding if 'charset' in req.headers.get('content-type', '').lower() else None
soup = BeautifulSoup(req.content, 'html.parser', from_encoding=encoding)

【讨论】:

  • 完美,谢谢。我犯了一个愚蠢的错误,但我今天学到了一些新东西:)。关于编码也很重要!
  • 通过req.text而不是req.content让requests而不是beautifulsoup处理解码不是更好吗?请求已经遇到了根据标头解码正文的麻烦;为什么让beautifulsoup再做一次?
  • @jwodder:不,因为 HTML 可以包含嵌入在 &lt;meta&gt; 标头中的编解码器。响应中的标头并不总是(通常不)准确,甚至不存在。
  • @jwodder: requests.text 是解码后的内容,但是因为 text/* 内容类型响应的默认编解码器是 Latin-1 请求将使用它来解码为 Unicode,这将 a) 总是工作并且b)通常是完全错误的并导致Mojibake。 BeautifulSoup 做了浏览器所做的事情:更喜欢 &lt;meta&gt; 标头信息,或者根据字符集检测做出有根据的猜测,如果没有提供有关所用编解码器的任何其他信息。
【解决方案2】:
import requests
from bs4 import BeautifulSoup

url = 'Your url'

def get_html(url):
    r = requests.get('https://m.vk.com/uporols_you').text
    soup = BeautifulSoup(r, 'lxml')

【讨论】:

  • 虽然此代码可能会回答问题,但提供有关它如何和/或为什么解决问题的额外上下文将提高​​答案的长期价值。
猜你喜欢
  • 2012-10-09
  • 2016-09-02
  • 1970-01-01
  • 1970-01-01
  • 2015-07-09
  • 1970-01-01
  • 2023-03-16
  • 2017-07-15
  • 1970-01-01
相关资源
最近更新 更多