【发布时间】:2016-10-09 14:55:48
【问题描述】:
我正在做一个网页抓取项目,我有以下项目我计划进行网页抓取:
<td class="country">
<div>
<img alt="Niger" height="27" src="http://assets.rio2016.nbcolympics.com/country-flags/52x35/NIG.png" width="40"/>
Niger
</div>
在这种情况下,我试图将国家尼日尔排除在列表之外。我有一整张桌子,我试图把所有国家都拉出来。我当前的代码如下所示:
response = requests.get('http://www.nbcolympics.com/medals')
soup = BeautifulSoup(response.content, 'lxml')
for td in soup.findAll("td",{"class": "country"}):
print(td)
这会让我获得很多信息。我只想关注表格中的国家/地区价值。 (此表包含所有参加奥运会的国家。)如果我尝试执行以下操作:
for td in soup.findAll("td",{"class": "country"}).children:
我收到以下错误消息:
Traceback (most recent call last):
File "idea.py", line 15, in <module>
for row in soup.find_all('tr').children:
AttributeError: 'ResultSet' object has no attribute 'children'
我知道必须有一种方法可以查看每个 td 以提取国家/地区价值。 (我可以使用 get_text() 获取国家/地区,但它附带了更多信息。)另外,如果 div 值有一个类,那么我认为它也很容易做到。感谢您的帮助。
我也试过了:
for td in soup.findAll("img", {"width": "40"})
print(td)
这几乎得到了我想要的。它将打印以下内容:
<img alt="Togo" height="27" src="http://assets.rio2016.nbcolympics.com/country-flags/52x35/TOG.png" width="40"/>
但是,我并没有在它之后得到这个国家!但我就在那里!
【问题讨论】:
标签: python python-3.x web-scraping beautifulsoup