使用selenium从网站中提取文本

2024-09-28 19:04:44 发布

您现在位置:Python中文网/ 问答频道 /正文

试图找到一种方法从好书页中摘录这本书的摘要。曾尝试过靓汤/硒,但不幸无效

链接:https://www.goodreads.com/book/show/67896.Tao_Te_Ching?from_search=true&from_srp=真&;qid=D19IQ7Kwi&;排名=1

代码:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from bs4 import BeautifulSoup
import requests
link='https://www.goodreads.com/book/show/67896.Tao_Te_Ching?from_search=true&from_srp=true&qid=D19iQu7KWI&rank=1'
driver.get(link)
Description=driver.find_element_by_xpath("//div[contains(text(),'TextContainer')]")
#first TextContainer contains the sumary of the book
book_page = requests.get(link)
soup = BeautifulSoup(book_page.text, "html.parser")
print(soup)
Container = soup.find('class', class_='leftContainer')
print(Container)

错误:

container is empty +

NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//div[contains(text(),'TextContainer')]"} (Session info: chrome=83.0.4103.116)


Tags: textfromhttpsimporttruewwwseleniumlink
1条回答
网友
1楼 · 发布于 2024-09-28 19:04:44

你可以这样得到描述

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
...
driver.get("https://www.goodreads.com/book/show/67896.Tao_Te_Ching?from_search=true&from_srp=true&qid=D19iQu7KWI&rank=1")
description = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.CSS_SELECTOR, 'div#description span[style="display:none"]'))
)
print(description.get_attribute('textContent'))

我使用了CSS Selector 来获取包含完整描述的特定隐藏span。我还使用了一个explicit wait来给元素加载时间

相关问题 更多 >