【问题标题】:Getting URLs from Page and also the next pages从页面和下一页获取 URL
【发布时间】:2020-03-07 00:29:46
【问题描述】:

我正在尝试从页面中获取所有 url 链接。我正在使用这个链接

https://www.horizont.net/suche/?OK=suchen&OK=suchen&i_sortfl=pubdate&i_sortd=desc&i_q=der

此链接基于显示不同文章的搜索查询。每页大约有9篇文章。所以我想从页面中获取所有 URL 链接作为列表。

我想尝试的第二步,当页面中的所有链接都从页面中提取出来时,它会自动打开第二个页面并从那里获取所有链接。

所以,s 大约有 15194 个页面,所以我想从页面中获取文章的所有超链接。

到目前为止,我正在尝试这样做:

from BeautifulSoup import BeautifulSoup
import urllib2
import re

def getLinks(url):
    html_page = urllib2.urlopen(url)
    soup = BeautifulSoup(html_page)
    links = []

    for link in soup.findAll('a', attrs={'href': re.compile("^http://")}):
        links.append(link.get('href'))

    return links

print( getLinks("https://www.horizont.net/suche/?OK=suchen&OK=suchen&i_sortfl=pubdate&i_sortd=desc&i_q=der") )

我现在面临的问题是我从网站上获取每个网址,但我只需要搜索结果以及搜索结果中的下一页。

【问题讨论】:

    标签: python beautifulsoup urllib2


    【解决方案1】:

    你可以使用你需要的链接的元素类属性来提取href:

    for link in soup.findAll ('a', attrs = {'href': re.compile ("^ http: //")}, class _ = "ArticleTeaserSearchResultItem_link"):
    

    如果你要浏览所有页面并收集所有文章的url,我可以建议你更改链接本身的Page值,直到链接有效:

    i = 1
    urls = []
    while True:
    
        url = f"https://www.horizont.net/suche/?OK=1&i_q=der&i_sortfl=pubdate&i_sortd=desc&currPage={i}"
        try:
            def getLinks(url):
                html_page = urllib2.urlopen(url)
                soup = BeautifulSoup(html_page)
                links = []
    
                for link in soup.findAll('a', attrs={'href': re.compile("^http://")}, class_="ArticleTeaserSearchResultItem_link"):
                    links.append(link.get('href'))
    
                return links
    
        urls.append(getLinks(url))
    
        except:
            break
    
        i += 1
    

    目前我还没有机会调试我的代码,但希望对您有所帮助。祝你好运!

    【讨论】:

    • 谢谢@mind-protector 似乎是最好的解决方案。让我检查一下。 :)
    • 我能问一下你为什么在这里使用url = f"https://www.horizont.net/suche/?OK=1&i_q=der&i_sortfl=pubdate&i_sortd=desc&currPage={i}你在提供url之前使用了“f”,为什么?
    • 因为我将参数 i 传递到这一行,从而浏览了本站的页面
    • 好的,谢谢。该函数从半小时开始运行,但我仍在等待输出
    • 有什么方法可以在运行时得到结果?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 2017-06-19
    • 2020-12-15
    • 2011-08-31
    • 1970-01-01
    相关资源
    最近更新 更多