【发布时间】:2014-06-14 08:53:45
【问题描述】:
我正在尝试解析文档http://www.consilium.europa.eu/uedocs/cms_data/docs/pressdata/en/ecofin/5923en8.htm。
我想提取Commission: 之前的所有内容。
(我需要 Beautifulsoup,因为第二步是提取国家和人名)
如果我这样做:
import urllib
import re
from bs4 import BeautifulSoup
url="http://www.consilium.europa.eu/uedocs/cms_data/docs/pressdata/en/ecofin/5923en8.htm"
soup=BeautifulSoup(urllib.urlopen(url))
print soup.find_all(text=re.compile("Commission"))
我得到的唯一结果是:
[u'The Governments of the Member States and the European Commission were represented as follows:']
这是单词的第一次出现,但不是我要查找的行。我认为这是因为该文件无效,但不确定。如果我查看源代码:
<B><U><P>Commission</B></U>:</P>
但如果我打印soup,我可以看到文本,标签重新排序:
<u><b>Commission</b></u>
我怎样才能得到这个元素"Commission:"?
我正在使用 python 2.7 和 Beautifoulsoup 4.3.2。
编辑:已解决!
按照alecxe的建议,我换了一行:
soup=BeautifulSoup(urllib.urlopen(url))
与
BeautifulSoup(urllib.urlopen(url), 'html.parser')
它现在可以工作了:)。 谢谢大家。
编辑:类似问题
我用相同的解决方案发现了类似的问题:
Beautiful Soup 4 find_all don't find links that Beautiful Soup 3 finds
【问题讨论】:
-
但是运行这个脚本我得到了总共 9 个字符串:第二个就是这里提到的那个。
-
好吧,我们没有得到相同的结果。是因为我的python/Beautifoulsoup版本吗?
-
我运行了您帖子中所写的内容,bs4 和 python 2.7。
标签: python html parsing html-parsing beautifulsoup