【问题标题】:why selenium is not detecting certain tags为什么硒没有检测到某些标签
【发布时间】:2021-06-04 21:40:13
【问题描述】:

我正在尝试从this website 中抓取某些文本。

问题:我无法获取与h1a 标记(在图片中突出显示)相关联的特定文本:“HTTP 方法--Get & POST”。但我可以访问class="entry-summary" 并获取它的文本。当我访问标签时,我得到的只是空字符串。为什么?

html 摘录为图片:

相关代码

main = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.ID, "main"))
)
#print(main.text)
articles = main.find_elements_by_tag_name("article")
header.append(articles[0].find_element_by_tag_name("a").text)

最低工作代码

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
from random import randint

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

url = "https://www.techwithtim.net/?s=test"

## Driver setup and access title

path = "../dater/driver/chromedriver"
driver = webdriver.Chrome(path)
driver.get(url)

## Extract main from the new page and then headers

main = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.ID, "main"))
)
#print(main.text)
articles = main.find_elements_by_tag_name("article")
header.append(articles[0].find_element_by_tag_name("a").text)
print(header)

【问题讨论】:

  • [这个][stackoverflow.com/a/64340305/5986651] 类似。建议使用:header.append(article.find_element_by_tag_name("a").get_attribute("textContent")) 而不是 header.append(articles[0].find_element_by_tag_name("a").text)。但我不明白为什么 selenium 不能通过.text 得到这个

标签: python selenium selenium-webdriver web-scraping


【解决方案1】:

也许你可以尝试使用获取元素

.get_attribute('href')

喜欢:

header.append(articles[0].find_element_by_tag_name("a").get_attribute('href'))
print(header)

希望这会有所帮助,似乎对我有用。

【讨论】:

  • 我不需要href。我需要textContent。这行得通。
【解决方案2】:

内容在屏幕上可见吗?还是您需要向下滚动才能访问它?它可能遥不可及,在这种情况下,您需要添加一个向下滚动的功能,例如:

main.execute_script("window.scrollTo(0, 10000)")

【讨论】:

  • 它不可见,因为我看不到它。但是网页已经加载了它。文本为白色和白色背景(看起来像)。我可以将鼠标悬停在文本上。我试过你的脚本,结果它不再输出我的标题了。不知道为什么。
猜你喜欢
  • 1970-01-01
  • 2011-11-14
  • 2021-01-09
  • 1970-01-01
  • 2014-11-16
  • 2021-01-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多