BeautifulSoup按列号指定表格?
我正在使用Python 2.7和BeautifulSoup 4来从一个表格中抓取歌曲名称。
现在我的脚本可以找到表格行中的链接;我想知道怎么指定只想要第一列的内容?
理想情况下,我希望能通过调整数字来选择不同的列。
目前我的代码是这样的:
from bs4 import BeautifulSoup
import requests
r = requests.get("http://evamsharma.finosus.com/beatles/index.html")
data = r.text
soup = BeautifulSoup(data)
for table in soup.find_all('table'):
for row in soup.find_all('tr'):
for link in soup.find_all('a'):
print(link.contents)
我该如何在每个<tr>
标签内索引<td>
标签呢?
现在的URL是我网站上的一个页面,我基本上是从维基百科复制了表格的源代码,以便让抓取变得简单一些。
谢谢!
evamvid
1 个回答
1
在每个
index = 2
for table in soup.find_all('table'):
for row in soup.find_all('tr'):
try:
td = row.find_all('td')[index]
except IndexError:
continue
for link in td.find_all('a'):
print(link.contents)