获取下一个元素,每个元素后面都匹配一个特定的类名



设置

我有下面的html表格,

<table>
<tbody>
<tr class="order-activ_order_delivered">
<tr class="tracking-url tracking-url-activ_order_delivered">
<tr class="order-activ_order_delivered">
<tr class="tracking-url tracking-url-activ_order_delivered">
<tr class="order-activ_order_delivered">
<tr class="tracking-url tracking-url-activ_order_delivered">
<tr class="order-complete">
<tr class="empty-tracking-url order-complete">
<tr class="order-activ_order_delivered">
<tr class="tracking-url tracking-url-activ_order_delivered">
<tr class="order-activ_order_delivered">
<tr class="tracking-url tracking-url-activ_order_delivered">
<tr class="order-complete">
<tr class="empty-tracking-url order-complete">
<tbody>
</table>

我只需要类名为"order-activ_order_delivered""tracking-url tracking-url-activ_order_delivered"的行中的信息。

此外,任何"order-activ_order_delivered"行的信息都与随后的"tracking-url tracking-url-activ_order_delivered"行相关。


迄今为止的代码

以下循环得到每个"order-activ_order_delivered"

order_table = el_css(browser,'#my-orders-table > tbody')
for order in order_table.find_elements(By.CSS_SELECTOR,
"tr[class^='order-activ_order_delivered']"):
#code to get data from row

问题

为了获得我尝试的后续"tracking-url tracking-url-activ_order_delivered"行的信息,

for order in order_table.find_elements(By.CSS_SELECTOR,
"tr[class^='order-activ_order_delivered']"):

order_table.find_elements(By.CSS_SELECTOR,
"tr[class^='order-activ_order_delivered']/following-sibling::tr")

但这给出了InvalidSelectorException: invalid selector: An invalid or illegal selector was specified (Session info: chrome=100.0.4896.127)

要么是因为不能在CSS_SELECTOR上使用following-sibling,要么是因为其他原因。

如何从随后的"tracking-url tracking-url-activ_order_delivered"行获取?

following-sibling不是CSS_Selector语法,而是xpath语法。

您的代码应该类似于识别特定元素,然后使用xpath检查following-sibling

for order in order_table.find_elements(By.CSS_SELECTOR,
"tr[class^='order-activ_order_delivered']"):
nextelement=order.find_element(By.XPATH, "./following-sibling::tr[@class='tracking-url tracking-url-activ_order_delivered']")

for order in order_table.find_elements(By.CSS_SELECTOR,
"tr[class^='order-activ_order_delivered']"):

nextelement=order.find_element(By.XPATH, "./following-sibling::tr[1]")

如果想使用css selector,可以使用它,它将返回所有跟踪url。

tr[class^='order-activ_order_delivered']+tr.tracking-url.tracking-url-activ_order_delivered

代码:

for order in order_table.find_elements(By.CSS_SELECTOR,
"tr[class^='order-activ_order_delivered']+tr.tracking-url.tracking-url-activ_order_delivered"):
nextelement=order

相关内容

  • 没有找到相关文章

最新更新