爬虫技术-- BeautifulSoup 标签选择的一个疑惑

2015-06-14 10:38:46 +08:00
 redhatping
from bs4 import BeautifulSoup
import re
html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<table>
<tr>
<th> biaoti </th>
<td> hi </td>
</tr>

</table>

<table>

<tr>
<th> biaoti2  </th>
<th>  biaoti3 </th>
</tr>

<tr>
<td>  hello </td>
<td>  <a  href= 'http://www.sina.com/blog'> world </a>  </td>

</tr>



</table>


</body>
</html>
"""

soup = BeautifulSoup(html_doc)
print soup.td.find_all('a')   #first td  ? how to chose second td

print soup.find_all(href = re.compile("blog"))

用第二种方法, 可以方便找到 <a>标签,

如果使用第一种方法,明显是找第一个td, 当然没有a了,有没有其他办法可以选择呢? 不使用re的情况下。

另外:v2ex Markdown- 怎么让python 高亮啊。。

5408 次点击
所在节点    Python
21 条回复
imn1
2015-06-15 10:21:34 +08:00
@xjx0524
这个没什么问题,空列表返回false,这种写法合理
嫌不好看,可以 var=findall(...); if var: 判断

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/198405

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX