首页 > 解决方案 > 如何使用 Python 和 Selenium 遍历网站正文

问题描述

首先,我的python知识非常初级,所以如果我问的是真的很愚蠢,我很抱歉,但是这里有。

我正在尝试使用 selenium 来阅读板(特别是 4chan 上的 /biz/ 目录)来跟踪我投资的项目的关键字,并在有讨论我的一个项目的线程时通知我。

到目前为止,我已经设法打开页面并找到我想要搜索的元素,使用:

from selenium import webdriver

PATH = "C:\Program Files (x86)\chromedriver.exe"
driver  = webdriver.Chrome(PATH)

driver.get('https://boards.4channel.org/biz/catalog')

threads = driver.find_element_by_id('threads').text

print(threads)
driver.quit()

这成功地将所有线程打印为文本,但现在我想遍历它们并只返回包含关键字“NFY”和“CORX”的行。我一直在使用关键字“DOGE”进行测试,因为很少提及我的。遍历此文本并仅返回包含我的关键字的行的最佳方法是什么?

标签: pythonseleniumiterationscreen-scraping

解决方案


如果你想返回线程,这应该可以。

threads = driver.find_elements_by_xpath("Path to individual threads")

searchText = ["DOGE", "NFY", "CORX"]

for t in searchText.lower():
    for i in range(len(threads)):
        if t in threads[i].text.lower():
            print(f"Thread: {threads[i].text}")

推荐阅读