2012-08-10 69 views
2

我正在使用Python和正则表达式来查找HTML文档,而不像大多数人所说的那样,它完美地工作,即使事情可能出错。无论如何,我决定美丽汤会更快,更容易,但我真的不知道如何让它做我做的正则表达式,这很容易,但很混乱。如何使用Beautiful Soup从HTML文档获取纯文本和URL?

我使用这个页面的HTML:

http://www.locationary.com/places/duplicates.jsp?inPID=1000000001

编辑:

下面是主要场所的HTML:

<tr> 
<td class="Large Bold" nowrap="nowrap">Riverside Tower Hotel&nbsp;</td> 
<td class="Large Bold" width="100%">80 Riverside Drive, New York, New York, United States</td> 
<td class="Large Bold" nowrap="nowrap" width="55">&nbsp;<input name="selectCheckBox" type="checkbox" checked="checked" disabled="disabled" />Yes 
</td> 
</tr> 

第一近似代替实例:

<td class="" nowrap="nowrap"><a href="http://www.locationary.com/place/en/US/New_York/New_York/54_Riverside_Dr_Owners_Corp-p1009633680.jsp" target="_blank">54 Riverside Dr Owners Corp</a></td> 
<td width="100%">&nbsp;54 Riverside Dr, New York, New York, United States</td> 
<td nowrap="nowrap" width="55"> 

当我的程序得到它并且使用Beautiful Soup使它更具可读性时,HTML出现与Firefox的“查看源”有点不同......我不知道为什么。

这些都是我的正则表达式:

PlaceName = re.findall(r'"nowrap">(.*)&nbsp;</td>', main) 

PlaceAddress = re.findall(r'width="100%">(.*)</td>\n<td class="Large Bold"', main) 

cNames = re.findall(r'target="_blank">(.*)</a></td>\n<td width="100%">&nbsp;', main) 

cAddresses = re.findall(r'<td width="100%">&nbsp;(.*)</td>\n<td nowrap="nowrap" width="55">', main) 

cURLs = re.findall(r'<td class="" nowrap="nowrap"><a href="(.*)" target="_blank">', main) 

前两个是主要的地方和地址。其余的是为其他地方的信息。在做完这些之后,我决定我只想要cNames,cAddresses和cURLs的前5个结果,因为我不需要91或其他任何东西。

我不知道如何用BS找到这种信息。我可以用BS做的所有事情都是找到特定的标签并用它们做事。这个HTML有点复杂,因为所有的信息。我想要的是在桌子和桌子标签也是一种混乱...

你如何得到这些信息,并只限于前5个结果呢?

谢谢。

+0

请在这里包括您的问题的HTML的相关部分对未来的读者有用。 – 2012-08-10 13:44:23

+0

没有通向HTML解析的道路。这意味着你必须花一些时间学习一些解析器,而BeautifulSoup是更容易的解析器之一。你真的不能用正则表达式来欺骗任务。 http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454真的。 – msw 2012-08-10 14:29:18

回答

3

人们说,你不能解析使用正则表达式HTML是有原因的,但这里有适用于您的正则表达式,原因很简单:你必须在你的正则表达式\n&nbsp;和那些能在变化随机在您尝试解析的页面上。发生这种情况时,您的正则表达式不匹配,您的代码将停止工作。

但是,你正在寻找做任务是非常简单的

from BeautifulSoup import BeautifulSoup 
soup = BeautifulSoup(open('this-stackoverflow-page.html')) 

for anchor in soup('a'): 
    print anchor.contents, anchor.get('href') 

得到所有的锚标签,他们出现在该页面的深层嵌套结构不管。下面是我行从三个行脚本的输出摘录:

[u'Stack Exchange'] http://stackexchange.com 
[u'msw'] /users/282912/msw 
[u'faq'] /faq 
[u'Stack Overflow']/
[u'Questions'] /questions 
[u'How to use Beautiful Soup to get plaintext and URLs from an HTML document?'] /questions/11902974/how-to-use-beautiful-soup-to-get-plaintext-and-urls-from-an-html-document 
[u'http://www.locationary.com/places/duplicates.jsp?inPID=1000000001'] http://www.locationary.com/places/duplicates.jsp?inPID=1000000001 
[u'python'] /questions/tagged/python 
[u'beautifulsoup'] /questions/tagged/beautifulsoup 
[u'Marcus Johnson'] /users/1587751/marcus-johnson 

这是很难想象更少的代码,可以做许多工作适合你。