我正在使用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 </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"> <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%"> 54 Riverside Dr, New York, New York, United States</td>
<td nowrap="nowrap" width="55">
当我的程序得到它并且使用Beautiful Soup使它更具可读性时,HTML出现与Firefox的“查看源”有点不同......我不知道为什么。
这些都是我的正则表达式:
PlaceName = re.findall(r'"nowrap">(.*) </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%"> ', main)
cAddresses = re.findall(r'<td width="100%"> (.*)</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个结果呢?
谢谢。
请在这里包括您的问题的HTML的相关部分对未来的读者有用。 – 2012-08-10 13:44:23
没有通向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