【问题标题】:Use BeautifulSoup to loop through and retrieve specific URLs使用 BeautifulSoup 循环和检索特定的 URL
【发布时间】:2015-12-28 09:28:07
【问题描述】:

我想使用 BeautifulSoup 并重复检索特定位置的特定 URL。您可以想象有 4 个不同的 URL 列表,每个列表包含 100 个不同的 URL 链接。

我需要始终获取并打印每个列表上的第三个 URL,而前一个 URL(例如第一个列表上的第三个 URL)将导致第二个列表(然后需要获取并打印第三个 URL 等等直到第 4 次检索)。

然而,我的循环只实现了第一个结果(列表 1 上的第三个 URL),我不知道如何将新 URL 循环回 while 循环并继续该过程。

这是我的代码:

import urllib.request
import json
import ssl
from bs4 import BeautifulSoup


num=int(input('enter count times: ' ))
position=int(input('enter position: ' ))

url='https://pr4e.dr-chuck.com/tsugi/mod/python-   
data/data/known_by_Fikret.html'
print (url)

count=0
order=0
while count<num:
    context = ssl._create_unverified_context()
    htm=urllib.request.urlopen(url, context=context).read()
    soup=BeautifulSoup(htm)
    for i in soup.find_all('a'):
        order+=1
        if order ==position:
            x=i.get('href')
            print (x)
    count+=1
    url=x        
print ('done')

【问题讨论】:

    标签: python loops url beautifulsoup


    【解决方案1】:

    这是一个使用递归的好问题。尝试调用递归函数来执行此操作:

    def retrieve_urls_recur(url, position, index, deepness):
        if index >= deepness:
            return True
        else:
            plain_text = requests.get(url)
            soup = BeautifulSoup(plain_text)
            links = soup.find_all('a'):
            desired_link = links[position].get('href')
            print desired_link
            return retrieve_urls_recur(desired_link, index+1, deepness) 
    

    然后在您的情况下使用所需的参数调用它:

    retrieve_urls_recur(url, 2, 0, 4)
    

    2是url列表中的url索引,0是计数器,4是你想要递归的深度

    ps:我使用的是requests而不是urllib,虽然我最近使用了一个非常相似的函数,但我没有对此进行测试

    【讨论】:

      【解决方案2】:

      只需按索引从find_all() 获取链接:

      while count < num:
          context = ssl._create_unverified_context()
          htm = urllib.request.urlopen(url, context=context).read()
      
          soup = BeautifulSoup(htm)
          url = soup.find_all('a')[position].get('href')
      
          count += 1
      

      【讨论】:

      • 这是解决我的问题的一种相当简单有效的方法,我不知道您可以将soup.find_all('a')[position].get('href') 设置为'two行动'在一起。感谢您的反馈,问题已解决!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-03-01
      • 2017-07-14
      • 2014-01-16
      • 1970-01-01
      • 2017-01-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多