检测所有名称并使用 Selenium Python 获取他们的 link

Detect all names and get their link with Selenium Python

我想做一个搜索系统,当我们在变量中输入一个词时,它会在所有链接的名称of this page(所有游戏)之间搜索,有点像 « control-F » 并显示结果(名称 + 链接)使用 Selenium (Python).

我不知道怎么做这样的系统!能帮忙就好了!

祝您代码愉快!

您正在尝试定位页面上的特定元素,然后对它们进行排序以获得关键搜索词。 Selenium 可以通过多种方法识别页面上的元素,see here for a guide。找到所有元素后,您可以根据感兴趣的搜索词过滤它们。

找到所有感兴趣的元素:

我会利用您元素的 XPATH 在页面上找到它们并制作一个列表,然后您可以根据关键字搜索该列表。在您的情况下,所有这些都可以通过此 xpath 识别:

//div[@class="blog-content"]//a

提取所需信息:

获得元素列表后,您需要遍历它们以提取 href 标签(游戏的 url)和 innerHTML 文本(游戏名称游戏)。

我在下面的例子中使用了列表理解来做到这一点,它创建了一个字典{url:name, ...}你可以从中过滤你的特定项目。

示例代码:

from selenium import webdriver  
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by      import By
from webdriver_manager.firefox import GeckoDriverManager

website_url = 'https://steamunlocked.net/all-games-2/'
game_xpaths = '//div[@class="blog-content"]//a'

driver = webdriver.Firefox(service=Service(GeckoDriverManager().install()))
driver.get(website_url)

game_elements = driver.find_elements(By.XPATH, game_xpaths)
games = {g.get_attribute('href'):g.get_attribute('innerHTML') for g in game_elements}
games

"""
Outputs:
{'https://steamunlocked.net/red-tether-free-download/': '—Red—Tether–> Free Download (v1.006)',
 'https://steamunlocked.net/hack-g-u-last-recode-free-download/': '.hack//G.U. Last Recode Free Download (v1.01)',
 'https://steamunlocked.net/n-verlore-verstand-free-download/': '‘n Verlore Verstand Free Download',
 'https://steamunlocked.net/0-n-0-w-free-download/': '0°N 0°W Free Download',
 'https://steamunlocked.net/007-legends-free-download/': '007 Legends Free Download', ...
"""

查找特定项目(即 CTRL+F)

根据您感兴趣的 word/string 的出现,仅从字典中识别和过滤特定项目。

def search(myDict, search_term):
    return [[v,k] for k,v in myDict.items() if search_term.lower() in v.lower()]

>>> search(games, 'Ninja')
[['10 Second Ninja Free Download','https://steamunlocked.net/10-second-ninja-free-download/'],
 ['10 Second Ninja X Free Download','https://steamunlocked.net/10-second-ninja-x-free-download/']]