使用python列出网页中的链接

使用python列出网页中的链接,python,request,Python,Request,我试图编写一个python脚本,列出网页中包含一些子字符串的所有链接。我遇到的问题是,这个网页有多个“页面”,这样就不会把所有的屏幕都弄得乱七八糟。请看一个例子 这就是我到目前为止所做的: import requests from bs4 import BeautifulSoup url = "https://www.go-hero.net/jam/17/solutions/1/1/C++" response = requests.get(url) soup = BeautifulSoup(re

我试图编写一个python脚本,列出网页中包含一些子字符串的所有链接。我遇到的问题是,这个网页有多个“页面”,这样就不会把所有的屏幕都弄得乱七八糟。请看一个例子

这就是我到目前为止所做的:

import requests
from bs4 import BeautifulSoup
url = "https://www.go-hero.net/jam/17/solutions/1/1/C++"
response = requests.get(url)
soup = BeautifulSoup(response.content, "html5lib")
links = soup.find_all('a')

for tag in links:
  link = tag.get('href', None)
  if link is not None and 'GetSource' in link:
    print(link)

有什么建议可以让我的工作?提前感谢。

编辑/更新:使用,您可以在抓取html之前单击页面链接,将所有内容收集到html中。许多/大多数具有分页功能的网站在单击页面时不会收集html中的所有文本,但我注意到您提供的示例确实如此。请看一个使Selenium与BeautifulSoup协同工作的快速示例。以下是如何在代码中使用它:

import requests
from bs4 import BeautifulSoup
from selenium import webdriver

driver = webdriver.Firefox()
original_url = "https://www.go-hero.net/jam/17/solutions/1/1/C++"
driver.get(original_url)

# click the links for pages 1-29
for i in range(1, 30):
    path_string = '/jam/17/solutions/1/1/C++#page-' + str(i)
    driver.find_element_by_xpath('//a[@href=' + path_string + ']').click()

# scrape from the accumulated html
html = driver.page_source
soup = BeautifulSoup(html)
links = soup.find_all('a')

# proceed as normal from here
for tag in links:
    link = tag.get('href', None)
    if link is not None and 'GetSource' in link:
        print(link)
原始答案:对于您提供的上述内容,您可以简单地通过可能的URL循环,并在循环中运行您的抓取代码:

import requests
from bs4 import BeautifulSoup
original_url = "https://www.go-hero.net/jam/17/solutions/1/1/C++"

# scrape from the original page (has no page number)
response = requests.get(original_url)
soup = BeautifulSoup(response.content, "html5lib")
links = soup.find_all('a')

# prepare to scrape from the pages numbered 1-29
# (note that the original page is not numbered, and the next page is "#page-1")
url_suffix = '#page-'

for i in range(1, 30):
    # add page number to the url
    paginated_url = original_url + url_suffix + str(i)
    response = requests.get(paginated_url)
    soup = BeautifulSoup(response.content, "html5lib")
    # append resulting list to 'links' list
    links += soup.find_all('a')

# proceed as normal from here
for tag in links:
    link = tag.get('href', None)
    if link is not None and 'GetSource' in link:
        print(link)

我不知道你是否介意你的结果会重复。您将在
链接列表中获得与代码当前相同的重复结果,但您可以将链接添加到集合或其他内容中,以轻松解决此问题。

这种方法的问题是,它实际上无法获取第2、3、4页等的链接。相反,我们会一次又一次地从第0页获取相同的链接。这可以通过从另一个页面中查找一些用户名来验证。我添加了一个更好的方法,并将原始方法保留在答案的底部。我添加的方法使用selenium实现您想要的功能。我相信最初的方法在加载第2、3、4页等页面时确实有效,但您是对的,它也总共加载了30次第0页。