【问题标题】:Want to get urls from search results and also from next pages想要从搜索结果和下一页中获取 url
【发布时间】:2023-03-31 19:27:01
【问题描述】:

我无法抓取网站上的数据。我能够抓取文本,但是当我尝试提取 url 时出现错误。

这是网址:https://www.horizont.net/suche/OK=1&i_q=der&i_sortfl=pubdate&i_sortd=desc&currPage=1

到目前为止,我正在使用这个:

r=requests.get('https://www.horizont.net/suche/OK=1&i_q=der&i_sortfl=pubdate&i_sortd=desc&currPage=1')
c = r.content
soup = BeautifulSoup(c, 'html.parser')
all = soup.find_all('a',  {'class': 'ArticleTeaserSearchResultItem_link'}, href = True)

for item in all:
    print(item.find_all('h2')[0].text)

输出:

Schweizer Illustrierte und L'illustré rücken näher zusammen 
"En Garde" und andere Geschichten über Mut und Beharrlichkeit 
Hüttenzauber - der TV-Spot zu Weihnachten 
Neuwagen in Deutschland müssen künftig DAB+ empfangen können 
Schiess Werbig mit neuen Storys 
Thjnk-Manager Sebastian Schlosser kommt als Chief Marketing Officer 
Die Einreichungsphase läuft bis zum 30. November 
Ipsos / Sinus / YouGov / Appinio / Axis / GfK 
Pro Sieben Sat 1 plant Audio-Streaming-Plattform 
Adidas und DFB blasen in Streifenoptik zum Angriff auf den EM-Titel

问题 1: 我仍然无法抓取搜索中的网址

问题 2: 搜索结果包含大约 15000 个页面,我想抓取所有网址。

【问题讨论】:

  • 你的网址不正确,应该是https://www.horizont.net/suche/?OK=1&i_q=der&i_sortfl=pubdate&i_sortd=desc&currPage=1

标签: python beautifulsoup request


【解决方案1】:

提供的链接不正确。我已更改链接。 但是,由于您提到您需要多达 15000 页,因此我为此制作了循环。 要获取所有链接,您需要从链接中获取 href 属性。

all_links=[]
for i in range(1,15001):
    url='https://www.horizont.net/suche/?OK=1&i_q=der&i_sortfl=pubdate&i_sortd=desc&currPage={}'.format(i)
    print("url: " +url)
    r = requests.get(url)
    c = r.content
    soup = BeautifulSoup(c, 'html.parser')
    all = soup.find_all('a', {'class': 'ArticleTeaserSearchResultItem_link'}, href=True)
    for item in all:
        print("https://www.horizont.net" + item['href'])
        all_links.append("https://www.horizont.net" + item['href'])

print(all_links)

现在,如果您最后执行print(all_links),您将获得 15000 个页面列表中的所有链接。

【讨论】:

  • 完美。这正是我想要的...... :)
猜你喜欢
  • 2020-06-27
  • 2013-01-30
  • 1970-01-01
  • 2020-03-19
  • 1970-01-01
  • 1970-01-01
  • 2019-10-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多