
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 高亮啊。。
1 lxy 2015-06-14 10:54:03 +08:00 通过点取属性的方式只能获得当前名字的第一个tag。直接 soup.find_all('a') 就能找到所有 a 标签了。官网有详细中文文档。 |
2 redhatping OP @lxy 是这样的, 我的意思是: 我想找 td 下 有 <a>标签的方法? 如果不是td下的, 不需要。 |
3 lxy /div> 2015-06-14 11:10:45 +08:00 我想到的方法是 link = soup.find_all('a'),然后循环判断 link[i].parent.name 是否为 td |
4 redhatping OP @lxy 谢谢, 是 一个思路,有没有高大快的方法呢。。各位 |
5 bianzhifu 2015-06-14 11:25:05 +08:00 我更喜欢pyquery |
6 zeroten 2015-06-14 12:23:51 +08:00 感觉pyquery更顺手些 |
8 imn1 2015-06-14 13:32:49 +08:00 一直 lxml + xpath…… 其实一直正则,偶尔 lxml |
9 Tink PRO xpath好用 |
10 ca1n 2015-06-14 14:01:42 +08:00 |
11 redhatping OP |
12 realityone 2015-06-14 16:14:21 +08:00 |
13 redhatping OP @realityone 只有find_all 和 find方法 ,没有findall 。 |
14 realityone 2015-06-14 17:26:24 +08:00 @redhatping 啊。。已经是 bs4 了啊。。 |
15 xjx0524 2015-06-14 17:30:05 +08:00 |
16 ca1n 2015-06-14 21:09:31 +08:00 @redhatping 非要把代码甩在你脸上才开心 >>> for i in bs(html).find_all('td'): ... for x in i.find_all('a'): ... print x 拿好不送 |
17 ca1n 2015-06-14 21:14:38 +08:00 for i in bs(html).find_all('td'): ....for x in i.find_all('a'): ........print x 上面格式乱了, 如果你要说这个不能运行那纯粹是你自己的问题了 |
18 redhatping OP @ca1n 当然可以, |
19 runningteeth 2015-06-14 22:30:36 +08:00 |
20 secondwtq 2015-06-14 23:08:59 +08:00 纯路过... 这两天撸前端,Polymer blablabla,看到这个主题第一反应居然是 document.querySelector... 以前 soup 和 pyquery 都用过一点,pyquery 用起来挺顺手,不过我记得貌似有坑,好像是换行处理不对还是什么来着... |