数据抓取时列表索引超出范围

时间:2015-11-29 23:23:22

标签: python indexing web-scraping beautifulsoup

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

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个用户的数据。但是我无法弄清楚我应该使用什么破坏条件或如何处理这个异常。

1 个答案:

答案 0 :(得分: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

上详细了解相关信息