python3 beautifulsoup 表格指定行_BeautifulSoup按数字指定表格列?

这篇博客介绍了如何通过Python2.7和BeautifulSoup4库来从HTML表格中提取特定列的数据。作者目前的代码遍历了表格中的链接,但目标是获取每行的第一列。通过修改代码,可以实现选择不同列的功能。解决方案是查找表格内的'td'标签,并通过索引来获取所需列,例如第2列(索引为1),然后继续寻找并打印该单元格内的链接内容。
摘要由CSDN通过智能技术生成

Using Python 2.7 and BeautifulSoup 4, I'm scraping song names from a table.

Right now the script finds links in the row of a table; how can I specify I want the first column?

Ideally I'd be able to switch numbers around to change which ones got selected.

Right now the code looks like this:

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)

How do I, in effect, index the

tags within each tag?

The URL in there right now is a page on my site where I basically copied the table source from Wikipedia to make the scraping a little simpler.

Thanks!

evamvid

解决方案

Find all td tags inside tr and get the one you need by index:

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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值