Python和BS4-在一定时间后停止读取

Python和BS4-在一定时间后停止读取,python,dictionary,web-scraping,beautifulsoup,bs4,Python,Dictionary,Web Scraping,Beautifulsoup,Bs4,第一次使用Python3并开始掌握它的窍门。作为练习,我试图从中读取表格(使用BeautifulSoup4),并将排名、艺术家、专辑和年份转换为字典。然后我想把字典放到MySQL数据库中。我能够从表中获取所有信息,并将它们放入变量中,然后放入字典,但我有一个小问题。表中的最后一个条目是播发,因此它不跟随它上面的其他表行。我只想读表的前100行。我在尝试读取广告行时出错 这是我的密码。求求你,任何帮助都会很好。此外,如果您看到我的代码中有任何错误,或者我本可以做得更好,请告诉我 所以它正在打印字典

第一次使用Python3并开始掌握它的窍门。作为练习,我试图从中读取表格(使用BeautifulSoup4),并将排名、艺术家、专辑和年份转换为字典。然后我想把字典放到MySQL数据库中。我能够从表中获取所有信息,并将它们放入变量中,然后放入字典,但我有一个小问题。表中的最后一个条目是播发,因此它不跟随它上面的其他表行。我只想读表的前100行。我在尝试读取广告行时出错

这是我的密码。求求你,任何帮助都会很好。此外,如果您看到我的代码中有任何错误,或者我本可以做得更好,请告诉我

所以它正在打印字典,一切看起来都很好,但在打印完所有字典后,它给了我一个错误

from bs4 import BeautifulSoup
from urllib.request import Request, urlopen

url = "http://rateyourmusic.com/customchart"
req = Request(url, headers={'User-Agent': 'Mozilla/5.0'})
soup = BeautifulSoup(urlopen(req))

table = soup.find("table", {"class" : "mbgen"})
totalList = []

for row in table.findAll("tr"):
    cells = row.findAll("td")
    rank = int(cells[0].find(class_="ooookiig").text)
    artist = cells[2].find(class_="artist").text
    album = cells[2].find(class_="album").text
    year = cells[2].find(class_="mediumg").text
    year = int(year[1:5])

    chartData = {"Rank":rank, "Artist":artist, "Album":album, "Year":year}
    totalList.append(chartData)
    print(chartData)

您可以使用计数器进行迭代,并在计数器达到100时停止,但我不太喜欢这样,代码将不再有用,例如,他们决定将元素数增加到200。我会使用一个简单的
try
块,如下所示:

for row in table.findAll("tr"):
    try:
        cells = row.findAll("td")
        rank = int(cells[0].find(class_="ooookiig").text)
        artist = cells[2].find(class_="artist").text
        album = cells[2].find(class_="album").text
        year = cells[2].find(class_="mediumg").text
        year = int(year[1:5])

        chartData = {"Rank":rank, "Artist":artist, "Album":album, "Year":year}
        totalList.append(chartData)
        print(chartData)
    except AttributeError:
        pass

这是因为解析器找不到该项

来自BS4:

如果find_all()找不到任何内容,它将返回一个空列表。如果find()找不到任何内容,则返回None

您可以使用try块,但我个人更喜欢手动检查:

for rownumber, row in enumerate(table.findAll('tr')):
    if rownumber < 100:
        #do something
对于行数,枚举中的行(table.findAll('tr'):
如果行数<100:
#做点什么

您能提供完整的回溯吗?回溯(最近一次调用):文件“C:\Programming\RateYourMusicCrawler\AlbumInfoCrawler.py”,第21行,秩=int(单元格[0]。查找(class=“ookiig”).text)AttributeError:“非类型”对象没有属性“text”!非常感谢你的披萨!!!立刻解决了我的问题。我还不习惯捕捉错误。再次感谢!!!