【问题标题】:coercing to Unicode: need string or buffer, Tag found强制转换为 Unicode:需要字符串或缓冲区,找到标记
【发布时间】:2013-11-23 22:04:40
【问题描述】:

我正在尝试进行网页抓取并使用以下代码:

import mechanize
from bs4 import BeautifulSoup

url = "http://www.indianexpress.com/news/indian-actions-discriminating-against-us-exp/1131015/"
br =  mechanize.Browser()
htmltext = br.open(url).read()
articletext = ""
soup = BeautifulSoup(htmltext)
for tag in soup.findAll('p'):
    articletext += tag.contents[0]
print articletext

但我收到以下错误:

Traceback (most recent call last):
  File "C:/Python27/crawler/express.py", line 15, in <module>
    articletext += tag.contents[0]
TypeError: coercing to Unicode: need string or buffer, Tag found

谁能帮我解决这个错误,我是 Python 编程新手。

【问题讨论】:

    标签: python python-2.7 web-scraping beautifulsoup web-crawler


    【解决方案1】:

    对于至少找到一个&lt;p&gt; 标记,tag.contents[0] 是一个Tag 对象,而不是文本。对于您找到的具体网址,它是一个&lt;hr&gt; 标签:

    >>> tag
    <p><hr> </hr></p>
    

    为什么不用tag.text 而不是tag.contents[0]

    for tag in soup.findAll('p'):
        articletext += tag.text
    

    【讨论】:

    • 是的,这有帮助。非常感谢。
    猜你喜欢
    • 2012-06-06
    • 1970-01-01
    • 2021-03-28
    • 2015-02-01
    • 2014-12-21
    • 2012-04-12
    • 2011-07-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多