有两种方法可以获取您拥有的页面的 url。这将取决于您在源代码中的内容。首先让我告诉你最简单的方法。
我以this link 为例来演示这两种方式。
网页将网页的关系链接到link 标记中的外部文档。他们还通过为rel 属性赋予值canonical 来提供网页的首选网址。
简单来说,如果您可以找到link 标签,其属性为rel,其值为canonical,那么该标签将有一个href,其值为网页的首选网址。
import requests
from bs4 import BeautifulSoup
request = requests.get('https://www.newscientist.com/article/2286166-pianists-fitted-with-robotic-thumb-can-learn-to-play-with-11-digits/')
# You can skip the above step and replace request.text(next line) with the source you have
soup = BeautifulSoup(request.text, 'lxml')
link = soup.find('link', {'rel': 'canonical'})
print(link['href'])
这会给我输出:
https://www.newscientist.com/article/2286166-pianists-fitted-with-robotic-thumb-can-learn-to-play-with-11-digits/
现在是耗时的一个(因为使用 Selenium),如果 html 代码中没有具有规范值的 link 元素,那么您必须切换到此。
这很耗时,因为我们要向 google 寻求帮助。标题主要是独一无二的。因此,如果您通常搜索网页的标题,第一个结果大多是所需的网页。为此,我们必须使用Selenium。 Scrapy 也可以使用,但我现在使用的是Selenium。
from webdriver_manager.chrome import ChromeDriverManager
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
# adding options
option = webdriver.ChromeOptions()
# option.add_argument('--headless')
option.add_argument("--log-level=3")
option.add_experimental_option('excludeSwitches', ['enable-logging'])
# initialize browser
CDM = ChromeDriverManager(log_level='0')
driver = webdriver.Chrome(CDM.install(), options=option)
driver.get('https://google.com')
time.sleep(1)
# Get the title using BS beforehand
title = 'Pianists fitted with robotic thumb can learn to play with 11 digits | New Scientist'
# EDIT 1 Updated the arguments of send_keys method
driver.find_element_by_xpath('/html/body/div[1]/div[3]/form/div[1]/div[1]/div[1]/div/div[2]/input').send_keys(title + Keys.ENTER)
time.sleep(1)
# EDIT 1 remove the next two lines
# driver.find_element_by_xpath('/html/body/div[1]/div[3]/form/div[1]/div[1]/div[3]/center/input[1]').click()
# time.sleep(1)
result = driver.find_element_by_class_name('yuRUbf')
link = result.find_element_by_tag_name('a').get_attribute('href')
print(link)
driver.quit()
输出还是一样的:
https://www.newscientist.com/article/2286166-pianists-fitted-with-robotic-thumb-can-learn-to-play-with-11-digits/
由于您有 6000 多个网页要浏览,我假设所有这些都来自不同的网站。如果他们来自同一个网站,那么很容易找出是否需要第一种或第二种方法。假设它们是网站的混合体,我建议将这两种方法混合使用。
如果第一种方法在运行时失败,只需创建一个dictionary 并使用title-html code 作为键值对。通过BS 完成所有页面后,现在通过运行字典开始使用Selenium。这比在循环中间随机切换Selenium 和BS 更好。
我建议使用字典而不是列表,仅包含标题,因为如果您想稍后比较源代码(以检查这是否正确)你可以有效地使用它。如果您不打算比较,请使用lists。
如果你很幸运,那么你不需要进入第二种类型,我希望你很幸运。这是一个很好的问题!
编辑 1:
更新了 Selenium 代码块以避免 Google Suggestions。