【问题标题】:Extracting Tags from BeautifulSoup从 BeautifulSoup 中提取标签
【发布时间】:2013-04-29 07:57:27
【问题描述】:

我正在尝试从 http://feeds.reuters.com/~r/reuters/technologyNews/~3/ZyAuZq5Cbz0/story01.htm 获取 Body-Tag

但 BeautifulSoup 没有找到它。这是因为无效的 HTML 吗?如果是这样,我该如何防止这种情况发生?

我还尝试使用 PyTidyLib (http://countergram.com/open-source/pytidylib/docs/index.html) 为 HTML 错误添加前缀

以下是部分代码:

def getContent(url, parser="lxml"):
    request = urllib2.Request(url)  
    try:    
        response = opener.open(request).read()
    except:
        print 'EMPTY CONTENT',url
        return None
    doc, errors = tidy_document(response)
    return parse(url, doc)

def parse(url, response, parser="lxml"):
    try:
        soup = bs(response,parser)
    except UnicodeDecodeError as e:
        if parser=="lxml":
            return parse(url, response, "html5lib")
        else:
            print e,url
            print 'EMPTY CONTENT',url
            return None  

    body = soup.body
    ...

当我打印出Soup时,我可以看到打开和关闭body-Tag,但是在body = soup.body之后,我得到了None。

我正在使用 Python 2.7.3 和 BeautifulSoup4 它似乎适用于 BeautifulSoup3,但由于性能问题,我需要坚持使用 BS4。

【问题讨论】:

标签: python beautifulsoup


【解决方案1】:

我终于让它运行起来了。 代码如下:

import urllib2
from lxml import html

url = "http://www.reuters.com/article/2013/04/17/us-usa-immigration-tech-idUSBRE93F1DL20130417?feedType=RSS&feedName=technologyNews"
response = urllib2.urlopen(url).read().decode("utf-8")
test = html.fromstring(response)

for p in test.body.iter('p'):
    print p.text_content()

【讨论】:

  • for p in test.body.iter('p'): .. ('p') 代表什么。是

    标签吗?

猜你喜欢
  • 2016-10-29
  • 2021-12-22
  • 2023-04-02
  • 1970-01-01
  • 2021-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多