Selenium/Python如何在使用Selenium扩展文本后获得全文?

2024-09-30 01:22:33 发布

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

我正在尝试从TripAdvisor中获取评论,对于长评论,只显示部分评论,需要单击“更多”才能显示完整的评论。我尝试在点击more后获取文本(我可以看到文本是展开的),但是我得到的只是部分评论。在

我的代码(用于获取一个特定的评论)如下:

driver = webdriver.Firefox()
driver.get(url)
review = driver.find_element_by_id("review_541350982") 
review.find_element_by_class_name("taLnk.ulBlueLinks").click()
driver.wait = WebDriverWait(driver, 5)
new_review = driver.find_element_by_id("review_541350982")
entry = new_review.find_element_by_class_name("partial_entry")
print entry.text

这是在单击“更多”之前的HTML:

^{pr2}$

以下是HTML:

<p class="partial_entry">This place blah blah blah What an incredible monument from both a historic and construction point of view.</p>
<span class="taLnk ulBlueLinks" onclick="widgetEvCall('handlers.clickCollapse',event,this);">Show less</span>

我注意到现在在单击“更多”后,<span>位于<p>之后。不知道这是否有用。在

任何建议都将不胜感激!在

编辑:注意到时间。睡觉(1) 而不是司机,等等解决了问题。想知道是否有更好的方法来实现这一点,即新条目在更改后自动获得,而不必设置任意的等待时间?在


Tags: name文本idbydriver评论elementfind
2条回答

找到评论并单击“更多”:

review = driver.find_element_by_id("review_541350982")
partial_text = review.find_element_by_tag_name('p')
partial_text.find_element_by_tag_name('span').click()

使用XPath重新定位审阅并输出文本:

^{pr2}$

高温

从您的代码中可以很明显地看出,WebDriverWait虽然已定义,但没有正确使用。要打印全文This place blah blah blah What an incredible monument from both a historic and construction point of view.,可以使用以下代码块:

from selenium.webdriver.support import expected_conditions as EC
#code block
review = driver.find_element_by_id("review_541350982") 
review.find_element_by_class_name("taLnk.ulBlueLinks").click()
new_review = driver.find_element_by_id("review_541350982")
full_review = WebDriverWait(driver, 10).until(EC.text_to_be_present_in_element(new_review.find_element_by_xpath("//p[@class='partial_entry']"),'This place blah blah blah What an incredible monument from both a historic and construction point of view.'))
entry = new_review.find_element_by_class_name("partial_entry")
print entry.text

相关问题 更多 >

    热门问题