python - 从 HTML 文件中提取信息

标签 python html

我正在尝试使用 Python 从大型 HTML 页面中提取特定信息/链接。例如,从下面给出的 IMDb 页面的 HTML 输出中,我尝试提取电影链接,如下所示:

href="/title/tt2388771/?ref_=nm_flmg_act_1" Jungle Book: Origins

使用以下Python代码似乎不起作用:

from urllib2 import urlopen
import re

source = urlopen("http://www.imdb.com/name/nm0000288/").read()

print re.findall('href="/title/', source)
print source

有什么帮助/建议吗?

<span class="ghost">|</span> <a href="#self"
onclick="handleFilmoJumpto(this);" data-category="self">Self</a></a>
<span class="ghost">|</span> <a href="#archive_footage"
onclick="handleFilmoJumpto(this);" data-category="archive_footage">Archive footage</a></a>
</div>
<div id="filmography">
<div id="filmo-head-actor" class="head" data-category="actor" onclick="toggleFilmoCategory(this);">
<span id="hide-actor" class="hide-link"
>Hide&nbsp;<img src="http://ia.media-imdb.com/images/G/01/imdb/images/icons/hide-1061525577._CB358668250_.png" class="absmiddle" alt="Hide" width="18" height="16"></span>
<span id="show-actor" class="show-link"
>Show&nbsp;<img src="http://ia.media-imdb.com/images/G/01/imdb/images/icons/show-582987296._CB358668248_.png" class="absmiddle" alt="Show" width="18" height="16"></span>
<a name="actor">Actor</a> (49 credits)
</div>
<div class="filmo-category-section"
>
<div class="filmo-row odd" id="actor-tt2388771">
<span class="year_column">
&nbsp;2017
</span>
<b><a href="/title/tt2388771/?ref_=nm_flmg_act_1"
>Jungle Book: Origins</a></b>
(<a href="/r/legacy-inprod-name/title/tt2388771" class="in_production">filming</a>)
<br/>
<a href="/character/ch0011743/?ref_=nm_flmg_act_1"
>Bagheera</a>
</div>
<div class="filmo-row even" id="actor-tt1596363">
<span class="year_column">
&nbsp;2016
</span>
<b><a href="/title/tt1596363/?ref_=nm_flmg_act_2"
>The Big Short</a></b>
(<a href="/r/legacy-inprod-name/title/tt1596363" class="in_production">filming</a>)
<br/>
Michael Burry
</div>

最佳答案

无需使用正则表达式在 HTML 文件中搜索信息。使用the worldwide famous Beautiful Soup相反。

您的用例示例:

from urllib2 import urlopen
from bs4 import BeautifulSoup
import re

source = urlopen("http://www.imdb.com/name/nm0000288/").read()

soup = BeautifulSoup(source)
soup.findAll('a', href=re.compile('^/title/'))

关于python - 从 HTML 文件中提取信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31522588/

相关文章:

Python 切片 - 除了括号中的内容以外的所有内容

javascript - JQuery 无法通过 val() 函数获取正确的值

html - 通过 URL scheme 将链接分享到 Telegram

python - opencv 和 python : how to use cv2. 带掩码的 surf()

python - 透视/取消堆叠具有重复条目的 DataFrame,无需聚合

html - CSS - 像素完美的汉堡包动画

javascript - 如何创建带点的 slider

javascript - 如何使用 addEventListener 访问 JavaScript 对象属性?

python - 漂亮的汤和解析reddit

python - 在特定字符后分割字符串