NO庫中提取所有的鏈接名稱...如何從一個html頁面
我嘗試從一個網頁得到所有的鏈接標題,代碼如下
url="http://einstein.biz/"
m = urllib.request.urlopen(url)
msg = m.read()
titleregex=re.compile('<a\s*href=[\'|"].*?[\'"].*?>(.+?)</a>')
titles = titleregex.findall(str(msg))
print(titles)
的標題分別爲
['Photo Gallery', 'Bio', 'Quotes', 'Links', 'Contact', 'official store', '\\xe6\\x97\\xa5\\xe6\\x9c\\xac\\xe8\\xaa\\x9e', '<img\\n\\t\\tsrc="http://corbisrightsceleb.122.2O7.net/b/ss/corbisrightsceleb/1/H.14--NS/0"\\n\\t\\theight="1" width="1" border="0" alt="" />']
這是不理想的,我想只有如下:
['Photo Gallery', 'Bio', 'Quotes', 'Links', 'Contact', 'official store']
如何修改我的代碼?
更換'(。+?)'與像您重新格局'([\ W \ S] +)' – kums 2014-10-31 07:18:14
這是真的很難用正則表達式解析HTML代碼。正則表達式(尤其是python正則表達式)不喜歡嵌套結構。但[BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/)是一個很好的工具來解析HTML ... – 2014-10-31 07:19:41
強制性鏈接[爲什麼你不應該用正則表達式解析HTML](http:// stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags) – miles82 2014-10-31 07:37:18