如何使用python 3中的硒从网站的一个部分获取文本

发布于 2025-02-02 20:11:37 字数 338 浏览 1 评论 0原文

我想知道如何使用Selenium和Python 3从网站上获取文字。我不知道文字是什么,所以我不能只是寻找句子并复制它。这是一个示例屏幕截图:示例问题。在这种情况下,我正在寻找少量数量1之后的文字。但是它是由:: header表示的,所以我很难抓住它。有什么想法吗?谢谢!另外,我从中获取的网站是 quia。

谢谢!

I was wondering how I can pull text from a website using Selenium and Python 3. I don't know what the text is, so I can't just look for the sentence and copy it. Here is an example screenshot: Example Problem. Know in this scenario I am looking for the small amount of text right after the 1. but it is represented by just ::header, so I am having trouble grabbing it. Any ideas? Thanks! Also the website I am pulling from is Quia.

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

何时共饮酒 2025-02-09 20:11:37

很难直接回答,因为此网络示例是在登录后面的。从广义上讲,您可以使用XPATH表达式,需要有关XML/HTML树的信息(例如,使用Chrome或Firefox时,PC键盘上的F12按钮可用。“ Inspect'contex鼠标菜单也是这样)。
在同一服务器的登录页面上示例以获取欢迎文本:

from selenium import webdriver
from selenium.webdriver.common.by import By

def s_obj(sel_drv, xph):
    return sel_drv.find_elements(by=By.XPATH, value = f"{xph}")

def s_text(sel_drv, xph):
    els = s_obj(sel_drv, xph)
    return '; '.join(el.text.replace('\n', '; ')\
        for el in els).strip(';').strip() if els else ''

test_url = "https://www.quia.com/web"

sel_drv = webdriver.Chrome()
sel_drv.get(test_url)
bs_xph = "//*/table/tbody/tr/td[@colspan=\"5\"]/h1[@class=\"home\"]"
expected_txt = s_text(sel_drv, f"{bs_xph}[1]")
print(expected_txt)
sel_drv.quit()

It's hard to answer directly because this web example is behind login. Broadly speaking you may use xpath expressions which needs information about xml/html tree(In example available under F12 button on PC keyboard when using Chrome or Firefox. „Inspect” from contex mouse menu is also the way).
Example on login page of same server to get welcome text:

from selenium import webdriver
from selenium.webdriver.common.by import By

def s_obj(sel_drv, xph):
    return sel_drv.find_elements(by=By.XPATH, value = f"{xph}")

def s_text(sel_drv, xph):
    els = s_obj(sel_drv, xph)
    return '; '.join(el.text.replace('\n', '; ')\
        for el in els).strip(';').strip() if els else ''

test_url = "https://www.quia.com/web"

sel_drv = webdriver.Chrome()
sel_drv.get(test_url)
bs_xph = "//*/table/tbody/tr/td[@colspan=\"5\"]/h1[@class=\"home\"]"
expected_txt = s_text(sel_drv, f"{bs_xph}[1]")
print(expected_txt)
sel_drv.quit()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文