python - 从最后一个超链接标签获取文本

标签 python html python-3.x selenium selenium-webdriver

我正在尝试访问超链接文本,这些文本将始终存储为嵌套在某个网站上的 100 个 div 标签中的最后一个超链接标签。在下面的示例中,“00A17”将是我尝试从单个标签中提取的内容。

HTML 代码:

<div class="headlineText">
  <a class="mrnum" title="Full MathSciNet Item" href="/mathscinet/search/publdoc.html?arg3=&amp;co4=AND&amp;co5=AND&amp;co6=AND&amp;co7=AND&amp;dr=all&amp;extend=1&amp;l=100&amp;pg4=AUCN&amp;pg5=TI&amp;pg6=PC&amp;pg7=ALLF&amp;pg8=ET&amp;review_format=html&amp;s4=&amp;s5=&amp;s6=&amp;s7=%22Featured%20Review%22&amp;s8=Journals&amp;sort=Newest&amp;vfpref=html&amp;yearRangeFirst=&amp;yearRangeSecond=&amp;yrop=eq&amp;r=9&amp;mx-pid=2650657"><strong>MR2650657</strong></a>
  <a class="item_status" href="/mathscinet/help/fullitem_help_full.html#indexed"><span>Indexed</span></a>
  <a href="/mathscinet/search/author.html?mrauthid=115370">Logan, J. David</a> <span class="title"><span class="searchHighlight">Featured review</span>: <span class="it">Introduction to the foundations of applied mathematics</span> [<a href="/mathscinet/search/publdoc.html?pg1=MR&amp;s1=2526777&amp;loc=fromrevtext">MR2526777</a>].</span>
  <a href="/mathscinet/search/journaldoc.html?id=5174"> <em>SIAM Rev.</em></a> <a href="/mathscinet/search/publications.html?pg1=ISSI&amp;s1=281478"> 52 </a>
  <a href="/mathscinet/search/publications.html?pg1=ISSI&amp;s1=281478"> (2010), </a>
  <a href="/mathscinet/search/publications.html?pg1=ISSI&amp;s1=281478"> no. 1,</a> 173–178.
  <a href="/mathscinet/search/mscdoc.html?code=00A17">00A17</a>
</div>

我为尝试此目的而编写的代码基本上是一团糟

用于远程访问的Python代码:

headlineTexts = []
mscLinks = []
for x in range(2,102):
    headlineTexts.extend(driver.find_elements_by_xpath("//*[@id='content']/form/div[3]/div[2]/div/div/div[%d]/div[2]"%x))
    mscLinks.extend(headlineTexts[x-2].find_elements_by_tag_name("a")[last()])

本质上,有 100 个“headlineText”div 标签(索引从 2 到 101),我需要从每个标签中获取上述超链接文本(因此需要迭代)。我基本上是创建一个 headerText 元素列表,然后对于每个 headerText 元素,我尝试提取带有标签名称“a”的最后一个子元素。不幸的是,当我尝试运行它时,我得到了

TypeError: 'WebElement' object is not iterable

这对我来说很奇怪,因为我只使用复数 find_elements() 并且应该生成一个可迭代列表。我是否可能错误地使用了last()?

最佳答案

检索超链接文本,该文本将始终存储为嵌套在某个网站上的 100 个 div 标签中的最后一个超链接标签,例如00A17您可以使用以下代码行:

print(driver.find_element_by_xpath("div[@class='headlineText']//a[last()]").get_attribute("innerHTML")) 

关于python - 从最后一个超链接标签获取文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48319723/

相关文章:

javascript - 从数据库中检索后将 CSS 类添加到 HTML 标签

python - 一次替换多个正则表达式模式

python - 我正在制作一个使用 8ball 的机器人,所以它说 'random' 不是 var 但我还能做什么,随机答案?

python - sqlalchemy 同时从 2 个表中计数

python - django 表格 : change attribute of formfield dynamically

python/matplotlib/seaborn- x 轴上带有数据点的箱线图

python - 使用 websocket-client 连接时出现 WinError 10057

c++ - python中编译模块之间的依赖关系

Wordpress 编辑器 + qtranslate = 跨度问题

javascript - 在javascript垂直转换期间在标题中保持动态字体颜色