我想從某個網站上抓取HTML,然後發送給BeautifulSoup進行解析。問題是由urllib2.urlopen()返回的HTML包含換行符(\ n)和製表符(\ t),以及單引號和其他字符轉義。當我嘗試使用此HTML構建BeautifulSoup對象時,出現錯誤。Urllib2返回帶有換行符和製表符的HTML
b = BeautifulSoup(src)
給出this error。
我的代碼:
def get_page_source(url):
"""
Retrieves the HTML source code for url.
"""
try:
return urllib2.urlopen(url)
except:
return ""
def retrieve_links(url):
"""
Use the BeautifulSoup module to efficiently grab all links from the source
code retrieved by get_page_source.
"""
src = get_page_source(url)
b = BeautifulSoup(src)
.
.
.
我怎樣才能解決這個問題?
編輯
import urllib2
link = "http://www.techcrunch.com/"
src = urllib2.urlopen(link).read()
f = open('out.txt', 'w')
f.write(src)
f.close()
我通常通過Tidy(它有一個Python模塊)運行我的HTML,然後用BeautifulSoup解析它。奇怪的是,我從未見過這種錯誤。您必須解析一些嚴重殘廢的HTML。 – Blender
這是我第一次遇到這個錯誤,之前我已經大量使用了urllib2。 – BrewerHimself