【问题标题】:BeautifulSoup errorsBeautifulSoup 错误
【发布时间】:2017-02-26 12:51:28
【问题描述】:

运行时出现错误。

import requests
from bs4 import BeautifulSoup

url = "http://sport.citifmonline.com/"
url_page_2 = "url" + "2016/10/15/chelsea-3-0-leicester-city-dominant-blues-comfortable-against-champions-photos/"
r = requests.get(url)

soup = BeautifulSoup(r.content, "html5lib")

links = soup.find_all("a")

for link in links:
    print "<a href='%s'>%s</a>" %(link.get("href"), link.text)

g_data = soup.find_all("div", {"class": "wrapper"})

for item in g_data:
    articles = item.content[0].find_all("a", {"class": "cat-box-content"})[0].text
    try:
        print item.contents[1].find_all("h3", {"class": "post-box-title"})[0].text
    except:
        pass

【问题讨论】:

  • 什么错误?请发布回溯。
  • 不是每个人都愿意或能够运行你的代码;但是,如果您准确地说明您遇到了什么错误并描述您已经尝试做些什么来解决问题,那么有些人可能仍然能够提供帮助。
  • 文件 "",第 2 行打印 "%s" %(link.get("href"), link.text) ^ IndentationError: 期望缩进块@Daniel
  • 在我修复缩进错误后,我得到了这个 Traceback(最近一次调用最后):文件“”,第 2 行,在 文件“C:\Python27\lib\encodings\ cp850.py",第 12 行,编码返回 codecs.charmap_encode(input,errors,encoding_map) UnicodeEncodeError: 'charmap' codec can't encode character u'\u2019' in position 103: character maps to @Daniel

标签: python beautifulsoup html-parsing


【解决方案1】:

如果您尚未安装 html5lib(例如使用 pip install html5lib),您将无法使用此解析器而不会出现错误。您可以安装它或去例如对于"html.parser" 而不是documentation of BeautifulSoup 中也提到的 - 只是为了避免任何错误:

soup = BeautifulSoup(r.content, "html.parser")

此外,您的内部/第二个for 循环的第一行会抛出一个TypeError,因为您正在尝试索引不可下标的东西(因为它不是列表或类似的东西,请参阅例如here for更多细节)。实际上,它甚至不存在 - 您尝试访问的属性 contentNone(当然不可下标)。您应该对每个元素直接调用find_all

item.find_all(...)

【讨论】:

  • Inb4 毫无意义的投反对票,没有任何建设性的批评。 :)
  • 可能是因为html5lib 是一个有效的解析器所以你的答案根本不正确,你的答案的第二部分也是错误的。
  • 谢谢,我用 pip install html5lib 做了。
猜你喜欢
  • 2012-05-18
  • 2016-07-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-16
  • 2015-04-22
相关资源
最近更新 更多