gpt4 book ai didi

Python - 列表索引超出范围 -

转载 作者:太空宇宙 更新时间:2023-11-03 21:08:18 24 4
gpt4 key购买 nike

我找到了一个脚本来编程,以用Python构建一个专注的爬虫。该脚本在函数 (google_scrape) 中停止。在此函数中,每当执行它时我都会遇到错误。此错误是(列表索引超出范围)你能帮我吗?

# Uses google search engine to find out the results for user query. 
def google_scrape(query):
address = "http://www.google.com/search?q=%s&num=100&hl=en&start=0" % (urllib.quote_plus(query))
request = urllib2.Request(address, None, {'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_4) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11'})
urlfile = urllib2.urlopen(request)
page = urlfile.read()
soup = BeautifulSoup(page)
links = []
count = 0
li = soup.findAll('li', attrs={'class':'g'})
while count < 10:
sLink = li[count].find('a')
links.append(sLink['href'])
count += 1
return links

错误堆栈: enter image description here

最佳答案

使用The limit argument :

li = soup.findAll('li', attrs={'class':'g'}, limit=10)

for elem in li:
sLink = elem.find('a')
links.append(sLink['href'])
count += 1

关于Python - 列表索引超出范围 -,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55255601/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com