【问题标题】:Extracting data from HTML-files with BeautifulSoup and Python使用 BeautifulSoup 和 Python 从 HTML 文件中提取数据
【发布时间】:2012-04-04 22:23:50
【问题描述】:

我需要从 HTML 文件中提取数据。有问题的文件很可能是自动生成的。我已将这些文件之一的代码上传到 Pastebin:http://pastebin.com/9Nj2Edfv。这是实际页面的链接:http://eur-lex.europa.eu/Notice.do?checktexts=checkbox&val=60504%3Acs&pos=1&page=1&lang=en&pgs=10&nbl=1&list=60504%3Acs%2C&hwords=&action=GO&visu=%23texte

我需要提取的数据位于不同的标题下。

这是我目前所拥有的:

from BeautifulSoup import BeautifulSoup
ecj_data = open("data\ecj_1.html",'r').read()

soup = BeautifulSoup(ecj_data)

celex = soup.find('h1')
auth_lang = soup('ul', limit=14)[13].li
procedure = soup('ul', limit=20)[17].li

print "Celex number:", celex.renderContents(),
print "Authentic language:", auth_lang
print "Type of procedure:", procedure

我将所有数据都存储在本地,这就是它打开文件 ecj_1.html 的原因。

Celex 号码和 Authentic 语言效果不错。

celex 返回

"Celex number: 
61977J0059"

auth_lang 返回"Authentic language: <li>French</li>"

我只需要 h1 标记的内容(而不是结尾处的中断)。

[另外,我需要 auth_lang 来返回“法语”,而不是 <li>-tags。] 这不再是问题。我意识到我可以将“.text”添加到“auth_lang”的末尾。

另一方面,过程返回:

    Type of procedure: <li>
    <strong>Type of procedure:</strong>
    <br />
    Reference for a preliminary ruling
    </li>

这是完全错误的,因为我只需要它返回“初步裁决的参考”。

有什么方法可以实现吗?

第二次修改: 我将celex = soup.find('h1') 替换为celex = soup('h1', limit=2)[0] 并将.text 添加到打印celex。

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:

    找到的每个序列的内容都是列表,只有前两个长度为 1。但是 procedure 的长度为 5 个元素,而您所追求的条目(在这种情况下)是第 4 个。我也使用splitlines() 来删除换行符。

    print "Celex number:", celex.contents[0].splitlines()[1]
    print "Authentic language:", auth_lang.contents[0].splitlines()[0]
    print "Type of procedure:", procedure.contents[4].splitlines()[1]
    

    输出:

    Celex number: 61977J0059
    Authentic language: French
    Type of procedure: Reference for a preliminary ruling
    

    【讨论】:

    • Fraxel:非常感谢!它就像一个魅力。这个想法是以某种方式将此文件的输出传输到数据库。我相信当您向我展示如何摆脱换行符时,您可能已经解决了未来的问题,因为它们可能会在以后搞砸。再次感谢!
    猜你喜欢
    • 2013-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-16
    • 1970-01-01
    • 2020-06-03
    相关资源
    最近更新 更多