Python Beautifulsoup4网站解析
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Python Beautifulsoup4网站解析,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2523字,纯文字阅读大概需要4分钟。
内容图文
![Python Beautifulsoup4网站解析](/upload/InfoBanner/zyjiaocheng/678/fc134e8dd6fd4f2a93d09bf6923182dd.jpg)
我正在尝试使用Beautifulsoup4从网站上抓取一些体育数据,但是在弄清楚如何进行操作时遇到了一些麻烦.我对HTML不太满意,而且似乎无法弄清楚必需的语法.解析完数据后,我将其插入Pandas数据框.我正在尝试提取主队,客队和得分.到目前为止,这是我的代码:
from bs4 import BeautifulSoup
import urllib2
import csv
url = 'http://www.bbc.com/sport/football/premier-league/results'
page = urllib2.urlopen(url).read()
soup = BeautifulSoup(page)
def has_class_but_no_id(tag):
return tag.has_attr('score')
writer = csv.writer(open("webScraper.csv", "w"))
for tag in soup.find_all('span', {'class':['team-away', 'team-home', 'score']}):
print(tag)
这是一个示例输出:
<span class="team-home teams">
<a href="/sport/football/teams/newcastle-united">Newcastle</a> </span>
<span class="score"> <abbr title="Score"> 0-3 </abbr> </span>
<span class="team-away teams">
<a href="/sport/football/teams/sunderland">Sunderland</a> </span>
我需要将主队(纽卡斯尔),比分(0-3)和客队(桑德兰)存储在三个不同的区域中.本质上,我一直在尝试从每个标记中提取“值”,并且似乎无法弄清bs4中的语法.我需要一个tag.value属性,但是我在文档中发现的只是tag.name或tag.attrs.任何帮助或指针将不胜感激!
解决方法:
每个得分单元位于< td class ='match-details'>内部.元素,将其循环以提取匹配详细信息.
在这里,您可以使用.stripped_strings生成器从子元素中提取文本;只需将其传递给”.join()即可获取标签中包含的所有字符串.分别选择家庭主场,得分和离队,以简化分析:
for match in soup.find_all('td', class_='match-details'):
home_tag = match.find('span', class_='team-home')
home = home_tag and ''.join(home_tag.stripped_strings)
score_tag = match.find('span', class_='score')
score = score_tag and ''.join(score_tag.stripped_strings)
away_tag = match.find('span', class_='team-away')
away = away_tag and ''.join(away_tag.stripped_strings)
附加打印可得到:
>>> for match in soup.find_all('td', class_='match-details'):
... home_tag = match.find('span', class_='team-home')
... home = home_tag and ''.join(home_tag.stripped_strings)
... score_tag = match.find('span', class_='score')
... score = score_tag and ''.join(score_tag.stripped_strings)
... away_tag = match.find('span', class_='team-away')
... away = away_tag and ''.join(away_tag.stripped_strings)
... if home and score and away:
... print home, score, away
...
Newcastle 0-3 Sunderland
West Ham 2-0 Swansea
Cardiff 2-1 Norwich
Everton 2-1 Aston Villa
Fulham 0-3 Southampton
Hull 1-1 Tottenham
Stoke 2-1 Man Utd
Aston Villa 4-3 West Brom
Chelsea 0-0 West Ham
Sunderland 1-0 Stoke
Tottenham 1-5 Man City
Man Utd 2-0 Cardiff
# etc. etc. etc.
内容总结
以上是互联网集市为您收集整理的Python Beautifulsoup4网站解析全部内容,希望文章能够帮你解决Python Beautifulsoup4网站解析所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。