html导出.csv在一列,BeautifulSoup/Python-将HTML表转换为CSV并获取一列的ref

您应该在第8个td标记中访问a标记的href属性:import csv

import urllib2

from bs4 import BeautifulSoup

records = []

for index in range(39):

url = get_url(index) # where is the formatting in your example happening?

response = urllib2.urlopen(url)

try:

html = response.read()

except Exception:

raise

else:

my_parse(html)

finally:

try:

response.close()

except (UnboundLocalError, NameError):

raise UnboundLocalError

def my_parse(html):

soup = BeautifulSoup(html)

table2 = soup.find_all('table')[1]

for tr in table2.find_all('tr')[2:]:

tds = tr.find_all('td')

url = tds[8].a.get('href')

records.append([elem.text.encode('utf-8') for elem in tds])

# perhaps you want to update one of the elements of this last

# record with the found url now?

# It's more efficient to write only once

with open('listing.csv', 'wb') as f:

writer = csv.writer(f)

writer.writerows(records)

我冒昧地基于索引定义了一个函数get_url,因为您的示例每次都会重读同一个文件,这是我猜您实际上并不需要的。我会把实现交给你。另外,我还添加了一些更好的异常处理。

同时,我还演示了如何从该网页的表中访问第二个表。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值