【问题标题】:How do i extract title of given url as string and store it in a text file in python2.7如何将给定url的标题提取为字符串并将其存储在python2.7的文本文件中
【发布时间】:2017-09-26 17:51:24
【问题描述】:

这是我写的python代码:

from bs4 import BeautifulSoup

url="http://www.thehindu.com/sci-tech/science/iit-bombay-birds-eye-view-and-quantum-biology/article18191268.ece"
htmltext = urllib.urlopen(url).read()
soup = BeautifulSoup(htmltext,"lxml")
webpage_title = soup.find_all('h1', attrs = {"class": "title"})
print webpage_title

这是我得到的输出:

 [<h1 class="title">\nIIT Bombay: Bird\u2019s eye view and quantum biology\n</h1>]

我希望输出是:

IIT Bombay: Bird’s eye view and quantum biology

我希望将此输出存储为字符串,以便我可以将其写入文件。

我不希望标题使用 unicode。

如果是这样,那么我想要一种将 unicode 转换为 ascii 字符串的方法。

【问题讨论】:

    标签: python-2.7 unicode beautifulsoup


    【解决方案1】:
    webpage_title = webpage_title[0].get_text(strip=True)
    

    默认情况下BS读取请求内容为utf-8

    【讨论】:

    • 用那个替换你的webpage_title = ...
    • 但是现在我如何将这个网页标题作为文本写入文件? UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 16: ordinal not in range(128).请帮忙解决这个问题。
    猜你喜欢
    • 2020-08-11
    • 1970-01-01
    • 2020-03-18
    • 2011-11-12
    • 2020-12-25
    • 2018-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多