【问题标题】:How can I make the code follow another link after the first one?如何使代码在第一个链接之后跟随另一个链接?
【发布时间】:2020-02-13 03:01:36
【问题描述】:

我试图在 url 的第 3 位找到链接(名字是 1)。按照那个链接。重复此过程 4 次。最后我想打印最后的链接。

我遇到的问题是让 url 重复。请给我一些建议,如何让这段代码运行。

import urllib.request, urllib.parse, urllib.error
import urllib
from urllib.request import urlopen
from bs4 import BeautifulSoup
import ssl
import re
lst = list()
lst2 = list()
count = 0
# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

url = 'http://py4e-data.dr-chuck.net/known_by_Fikret.html'
count = int(input('Enter Count '))
position = int(input('Enter Position ')) -1
while count >= 0:
    html = urlopen(url, context=ctx).read()
    soup = BeautifulSoup(html, "html.parser")
    tags = soup('a')
    for tag in tags:
        values = tag.get('href', None)
        values = str(values)
        lst.append(values)
        count = count - 1
        lst2.append(lst[position:position+1])
        url = lst2[0]
        url = str(url)
        print(re.findall('http.+html',url))
        lst.clear()
        lst2.clear()
    return url

【问题讨论】:

  • 您将在第一个循环结束时返回 url。您能否更改缩进以匹配while count >= 0 行?
  • 如果我正确理解您的问题,您想阅读第一个 URL,在 position-th 位置获取链接(在您的情况下为第 3 个),然后阅读第二个 URL,然后重复 @ 987654325@ 次(在您的情况下为 4 次)。 (顺便说一句,你不需要lstlst2;他们现在只是混淆了代码。)
  • 是的,你是对的,这是最终起作用的代码。

标签: python-3.x web screen-scraping


【解决方案1】:

如果我正确地解析了你的问题,一种方法(我将把错误检查作为练习留给你;代码也没有运行)是这样的:

# Loop count times; "_" effectively means ignore the counter
for _ in range(count):
    # Get an array of <a> elements,
    #   then get the (position-1)th
    #   then get the text of the 'href' tag
    next_url = soup.find_all('a')[position-1]['href']
    # And repeat for the URL found there
    html = urlopen(next_url, context=ctx).read()
    soup = BeautifulSoup(html, "html.parser")

# Finally, print out the (position-1)th URL on the last page
print(soup.find_all('a')[position-1]['href'])

当然,如果页面上没有足够的链接,或者有&lt;a&gt;标签没有href,或者href URL格式错误,程序就会崩溃。

【讨论】:

    【解决方案2】:

    在使用代码一段时间后,我能够回答我自己的问题。我确信有一个更有说服力的解决方案,但我真的很高兴我终于让它正确运行了。

    from urllib.request import urlopen
    from bs4 import BeautifulSoup
    import ssl
    import re
    lst = list()
    count = 0
    # Ignore SSL certificate errors
    ctx = ssl.create_default_context()
    ctx.check_hostname = False
    ctx.verify_mode = ssl.CERT_NONE
    
    url = 'http://py4e-data.dr-chuck.net/known_by_Fikret.html'
    count = int(input('Enter Count '))
    position = int(input('Enter Position ')) -1
    while True:
        html = urlopen(url, context=ctx).read()
        soup = BeautifulSoup(html, "html.parser")
        tags = soup('a')
        for tag in tags:
            values = tag.get('href', None)
            values = str(values)
            lst.append(values)
        url = str(lst[position:position+1])
        url = url[2:-2]
        print(url)
        lst.clear()
        count = count -1
        if count == 0:break
    

    【讨论】:

      猜你喜欢
      • 2021-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-16
      • 2023-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多