Python-如何获取所有实例,而不仅仅是页面上的第一个实例 [英] Python - How to get all instances instead of just the first on the page

查看:74
本文介绍了Python-如何获取所有实例,而不仅仅是页面上的第一个实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用findAll会出现错误"TypeError:列表索引必须是整数,而不是str",而使用.find则没有.使用findall会给出错误"TypeError:'NoneType'对象不可调用".

Using findAll gives the error "TypeError: list indices must be integers, not str", where using .find didn't. Using findall gives the error "TypeError: 'NoneType' object is not callable".

定位所有在页面上具有框架"类而不是仅是第一个实例的链接的正确方法是什么?

What is the correct way to target all links that have a class of "frame" on the page, instead of just the first instance?

import requests
from bs4 import BeautifulSoup

url = ("http://www.gym-directory.com/listing-category/gyms-fitness-centres/")
r = requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser')
print soup.findAll("a",{"class":"frame"})["href"]

url = ("http://www.gym-directory.com/listing-category/gyms-fitness-centres/page/2/")
r = requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser')
print soup.findAll("a",{"class":"frame"})["href"]

url = ("http://www.gym-directory.com/listing-category/gyms-fitness-centres/page/3/")
r = requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser')
print soup.findAll("a",{"class":"frame"})["href"]

url = ("http://www.gym-directory.com/listing-category/gyms-fitness-centres/page/4/")
r = requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser')
print soup.findAll("a",{"class":"frame"})["href"]

url = ("http://www.gym-directory.com/listing-category/gyms-fitness-centres/page/5/")
r = requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser')
print soup.findAll("a",{"class":"frame"})["href"]

url = ("http://www.gym-directory.com/listing-category/gyms-fitness-centres/page/6/")
r = requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser')
print soup.findAll("a",{"class":"frame"})["href"]

url = ("http://www.gym-directory.com/listing-category/gyms-fitness-centres/page/7/")
r = requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser')
print soup.findAll("a",{"class":"frame"})["href"]

url = ("http://www.gym-directory.com/listing-category/gyms-fitness-centres/page/8/")
r = requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser')
print soup.findAll("a",{"class":"frame"})["href"]

url = ("http://www.gym-directory.com/listing-category/gyms-fitness-centres/page/9/")
r = requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser')
print soup.findAll("a",{"class":"frame"})["href"]

推荐答案

问题是soup.findAll()返回一个list,而您正尝试使用["href"]

The issue is that soup.findAll() returns a list, and you are trying to access that list with ["href"]

您需要做的是:

for elem in soup.findAll("a", {"class": "frame"}):
    print elem["href"]

这篇关于Python-如何获取所有实例,而不仅仅是页面上的第一个实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆