【问题标题】:list index out of range while data scraping数据抓取时列表索引超出范围
【发布时间】:2015-11-29 23:23:22
【问题描述】:

您好,我正在尝试从网站上抓取用户数据。我正在使用以下代码

soup = BeautifulSoup(r.content)
a=0
pattern = regex.compile(r"UID_(\w+)\-SRC_\d+")
for user in soup.find_all(attrs={"class":"memberOverlayLink"}):
        id = soup.find_all("div",id=pattern)[a]["id"]
        uid=pattern.match(id).group(1)
        print(uid)
        a=a+1

在获得前 10 个结果后,我得到了这个结果

623946C8E24FB61D64DC19129ED61306
82E2983AA905CACB8CABF565BDDC1BFF
97598DF4333C7D9C430F29D02CF35304
FF9B4B5BB920DE1274286D57043221C7
E61CB7A638FA90F9A714BD0A70D5E730
6CD8A7AEFC3786FB7B353DCDD2A0BF48
4A0C7A5F824ED470C149A032D23DCA28
FB9F5FA7A0F1FD2B647F319B807A6072
088E6A96810B1B797F4BFE8386289BFD
60CE07D6DF5C02A987ED7B076F4154F3
Traceback (most recent call last):
File "C:/Utkarsh/Brookfield/TripAdvisorPython-master/New_Scrapetest.py",    line 9, in <module>
id = soup.find_all("div", id=pattern)[a]["id"]
IndexError: list index out of range

我注意到他们只是首页上 10 个用户的数据。但我无法弄清楚我应该使用什么中断条件或如何处理此异常。

【问题讨论】:

    标签: python indexing web-scraping beautifulsoup


    【解决方案1】:

    你可以用这个:

    soup = BeautifulSoup(r.content)
    a=0
    pattern = regex.compile(r"UID_(\w+)\-SRC_\d+")
    for user in soup.find_all(attrs={"class":"memberOverlayLink"}):
            try:
                id = soup.find_all("div",id=pattern)[a]["id"]
                uid=pattern.match(id).group(1)
                print(uid)
                a=a+1
            except IndexError:
                break
    

    我基本上为此使用了try/except 块。你可以在https://docs.python.org/2/tutorial/errors.html阅读更多关于它的信息

    【讨论】:

    • 乐于助人。也请将此标记为已接受,以便它可以帮助其他开发人员。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多