基本上,我正在尝试使用BeautifulSoup在python中抓取表格。
我已经设法抓取了其他链接数组中的所有数据,但由于某种原因,当我添加 .text
时,它会同时打印文本和 span 标签内的文本。不需要范围文本。
我试图做.string
和.text.text
,但它似乎不起作用。
任何人都可以在这里发现问题吗?
这是我的代码:
soup = BeautifulSoup(urllib2.urlopen('http://www.livefootballontv.com/').read())
for row in soup('div', {'id': 'tv-guide'})[0]('ul'):
tds = row('li')
print tds[0].string, tds[1].text, tds[1].span.string, tds[2].string, tds[3].img['alt'], 'n'
db = MySQLdb.connect("127.0.0.1","root","","footballapp")
cursor = db.cursor()
sql = "INSERT INTO TVGuide(DATE, FIXTURE, COMPETITION, KICKOFF, CHANNELS) VALUES (%s,%s,%s,%s,%s)"
results = (str(tds[0].string), str(tds[1]).text, str(tds[1].span.string), str(tds[2].string), str(tds[3].img['alt']))
cursor.execute(sql, results)
db.commit()
db.rollback()
db.close()
然后我被给予
2014年6月22日星期日 美国 vs 葡萄牙巴西世界杯 2014年G组 2014年巴西世界杯G组 11:00pm BBC1
星期二 24 六月 2014 哥斯达黎加 vs 英格兰巴西世界杯 2014 小组赛 D 巴西世界杯 2014 D组 下午5:00 ITV
使用 contents
,然后访问所需的条目。
例:
from bs4 import BeautifulSoup
import urllib2
soup = BeautifulSoup(urllib2.urlopen('http://www.livefootballontv.com/').read())
for row in soup('div', {'id': 'tv-guide'})[0]('ul'):
tds = row('li')
print tds[1].contents[0]
输出:
SV Hamburg vs Bayern Munich
Arsenal vs Manchester United
Napoli vs Roma
...
USA vs Portugal
Costa Rica vs England