使用BeautifulSoup从网页检索链接

时间:2019-09-16 23:43:25

标签: python

我试图从某个位置的网页上提取链接,然后打开该链接,然后重复该过程指定的次数。问题是我不断返回相同的URL,所以看来我的代码只是拉标签,打印标签,不打开标签,并在关闭前进行X次此过程。

我已经多次编写并重新编写了此代码,但是对于我一生,我只是无法弄清楚。请告诉我我在做什么错

尝试使用列表放置锚标记,然后在列表中请求的位置打开url,然后清除列表,然后再次开始循环。

import urllib.request, urllib.parse, urllib.error
from bs4 import BeautifulSoup
import ssl

# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

#url = input('Enter - ')
url = "http://py4e-data.dr-chuck.net/known_by_Fikret.html"
html = urllib.request.urlopen(url, context=ctx).read()
soup = BeautifulSoup(html, 'html.parser')

count = 0 
url_loop = int(input("Enter how many times to loop through: ")) 
url_pos= int(input("Enter position of URL: "))
url_pos = url_pos - 1

print(url_pos)



# Retrieve all of the anchor tags
tags = soup('a')
while True:
    if url_loop == count:
        break
    html = urllib.request.urlopen(url, context=ctx).read()
    soup = BeautifulSoup(html, 'html.parser')
    url = tags[url_pos].get('href', None)

    print("Acquiring URL: ", url)

    count = count + 1  

print("final URL:", url)

1 个答案:

答案 0 :(得分:0)

可能是对于初始文档,标签仅提取了一次:

# Retrieve all of the anchor tags
tags = soup('a')

如果要在提取每个文档后重新提取标签,它们会反映出最后一个文档。