使用请求和beautifulsoup迭代Python中的页面

2024-04-19 00:51:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从一个网站上提取链接。这个网页不止一个页面,所以我使用一个循环来遍历不同的页面。但问题是soup和new links中的内容只是重复的。中使用的URL请求.get我已经仔细检查了这个链接,以确保URL的内容发生了变化,而且确实如此。在

无论循环的迭代次数如何,新的连接都保持不变

有人能解释一下我怎么能解决这个问题吗?在

def get_links(root_url):

    list_of_links = []

    # how many pages should we scroll through ? currently set to 20
    for i in range(1,3):
        r = requests.get(root_url+"&page={}.".format(i))
        soup = BeautifulSoup(r.content, 'html.parser')
        new_links = soup.find_all("li", {"class": "padding-all"})
        list_of_links.extend(new_links)

    print(list_of_links)

    return list_of_links

Tags: ofurl网页内容newget网站链接
1条回答
网友
1楼 · 发布于 2024-04-19 00:51:08

您需要枚举您正在查找的li中的链接。最好将它们添加到set()中以删除重复项。然后可以在返回时将其转换为已排序的列表:

from bs4 import BeautifulSoup
import requests

def get_links(root_url):
    set_of_links = set()

    # how many pages should we scroll through ? currently set to 20
    for i in range(1, 3):
        r = requests.get(root_url+"&page={}".format(i))
        soup = BeautifulSoup(r.content, 'html.parser')

        for li in soup.find_all("li", {"class": "padding-all"}):
            for a in li.find_all('a', href=True):
                set_of_links.update([a['href']])

    return sorted(set_of_links)

for index, link in enumerate(get_links("http://borsen.dk/soegning.html?query=iot"), start=1):
    print(index, link)

给你:

^{pr2}$

如果只搜索next page按钮中的链接,而不是猜测要迭代多少页,这可能更有意义,例如:

from bs4 import BeautifulSoup
import requests

def get_links(root_url):
    links = []

    while True:
        print(root_url)
        r = requests.get(root_url)
        soup = BeautifulSoup(r.content, 'html.parser')

        for li in soup.find_all("li", {"class": "padding-all"}):
            for a in li.find_all('a', href=True)[:1]:
                links.append(a['href'])

        next_page = soup.find("div", {"class": "next-container"})

        if next_page:
            next_url = next_page.find("a", href=True)

            if next_url:
                root_url = next_url['href']
            else:
                break
        else:
            break

    return links

相关问题 更多 >