网页编号不同的网页抓取

时间:2020-10-23 05:45:32

标签: python web-scraping

因此,我正在尝试对一系列配置文件进行网络抓取。每个个人资料都有一组视频。我正在尝试网络搜集有关每个视频的信息。我遇到的问题是每个配置文件上载的视频数量不同,因此每个配置文件中包含视频的页面数量各不相同。例如,一个个人资料包含45页视频,如下面的html所示:

<div class="pagination "><ul><li><a class="active" href="">1</a></li><li><a href="#1">2</a></li><li><a href="#2">3</a></li><li><a href="#3">4</a></li><li><a href="#4">5</a></li><li><a href="#5">6</a></li><li><a href="#6">7</a></li><li><a href="#7">8</a></li><li><a href="#8">9</a></li><li><a href="#9">10</a></li><li><a href="#10">11</a></li><li class="no-page"><a href="#" class="ellipsis last-ellipsis">...</a><li><a href="#44" class="last-page">45</a></li><li><a href="#1" class="no-page next-page"><span class="mobile-hide">Next</span>

另一个个人资料有2个页面

<div class="pagination "><ul><li><a class="active" href="">1</a></li><li><a href="#1">2</a></li><li><a href="#1" class="no-page next-page"><span class="mobile-hide">Next</span>

我的问题是,如何解释页面的变化?我当时想制作一个for循环,然后在最后添加一个随机数,例如

for i in range(0,1000): 
  new_url = 'url' + str(i)

我在页面上占的位置,但是我想知道是否有一种更有效的方法。

谢谢。

3 个答案:

答案 0 :(得分:0)

  1. 获取<li>...</li>的{​​{1}}元素
  2. 按类别<div class="pagination "><ul>排除最后一个
  3. 解析“ href” 并构建您的下一个URL目标。
  4. 删除每个新的网址目标。

答案 1 :(得分:0)

循环的“骨架” 看起来像这样:

url = 'http://url/?page={page}'

page = 1
while True:
    soup = BeautifulSoup(requests.get(url.format(page=page)).content, 'html.parser')

    # ...

    # do we have next page?
    next_page = soup.select_one('.next-page')
    
    # no, so break from the loop
    if not next_page:
        break

    page += 1

您可以有无限循环while True:,只有在没有下一页(如果最后一页上没有class="next-page"标签的情况下),您才可以中断循环。

答案 2 :(得分:0)

我只想感谢所有花时间回答我的问题的回答者。我想出了答案-或至少对我有用,并决定分享一下,以防对其他人有帮助。

url = 'insert url'
re = requests.get(url)
soup = BeautifulSoup(re.content,'html.parser')

#look for pagination class
page = soup.find(class_='pagination')

#create list to include all page numbers
href=[]

#look for all 'li' tags as the users above suggested
links = page.findAll('li')
for link in links:
   href += [link.find('a',href=True).text]  

'''
href will now include all pages and the word Next. 
So for instance it will look something like this:[1,2,3...,44,Next]. 
I want to get 44, which will be href[-2] and then convert that to an int for 
a for loop. In the for loop add + 1 because it will iterate to i-1, instead of 
i. For instance, if you're iterating (0,44), the last output of i will be 43, 
which is why we +1
'''

for i in range(0, int(href[-2])+1):
   new_url = url + str(1)