需要帮助解析 html 元素并执行脚本无效
Need help parsing html element and execute script no worked
<li tabindex="0" role="tab" aria-selected="false">
<a href="#gift-cards" class="leftnav-links kas-leftnav-links" data-section="gift-cards" data-ajaxurl="/wallet/my_wallet.jsp">
<span class="width200 kas-gift-cards-tab">Gift Cards</span>
<span class="count kas-count">info</span>
</a>
</li>
我有这样一个 html 代码,它在一个页面上重复了大约 5 次,而这些块中只有 2 个包含我需要的信息。他们的 类 是一样的,我不知道该怎么办。
另外,Firefox 中的 execute_script 对我不起作用。
html_list = driver.find_element_by_id("rewards-contents")
items = html_list.find_element_by_tag_name("li")
for item in items:
text = item.text
print(text)
我试着在 python 上启动它,但没有任何结果。
我希望脚本显示所有 5 个区块的信息。
要获取所有元素,请使用 find_elements
而不是 find_element
。您的代码应如下所示:
html_list = driver.find_element_by_id("rewards-contents")
items = html_list.find_elements_by_tag_name("li")
for item in items:
print(item.text)
要通过 span
个元素获取文本:
html_list = driver.find_elements_by_css_selector("#rewards-contents li")
items = html_list.find_elements_by_tag_name("span")
for item in items:
print(item.text)
感谢@Sers 对 css_selector
的提示。我通过以下方式解决了我的问题:
`info = []
time.sleep(2)
htmllist = driver.find_element_by_class_name("rewards-contents")
items = htmllist.find_elements_by_css_selector(".kas-count")
for item in items:
info.append(item.text)
print(item.text)
print(info)`
<li tabindex="0" role="tab" aria-selected="false">
<a href="#gift-cards" class="leftnav-links kas-leftnav-links" data-section="gift-cards" data-ajaxurl="/wallet/my_wallet.jsp">
<span class="width200 kas-gift-cards-tab">Gift Cards</span>
<span class="count kas-count">info</span>
</a>
</li>
我有这样一个 html 代码,它在一个页面上重复了大约 5 次,而这些块中只有 2 个包含我需要的信息。他们的 类 是一样的,我不知道该怎么办。 另外,Firefox 中的 execute_script 对我不起作用。
html_list = driver.find_element_by_id("rewards-contents")
items = html_list.find_element_by_tag_name("li")
for item in items:
text = item.text
print(text)
我试着在 python 上启动它,但没有任何结果。
我希望脚本显示所有 5 个区块的信息。
要获取所有元素,请使用 find_elements
而不是 find_element
。您的代码应如下所示:
html_list = driver.find_element_by_id("rewards-contents")
items = html_list.find_elements_by_tag_name("li")
for item in items:
print(item.text)
要通过 span
个元素获取文本:
html_list = driver.find_elements_by_css_selector("#rewards-contents li")
items = html_list.find_elements_by_tag_name("span")
for item in items:
print(item.text)
感谢@Sers 对 css_selector
的提示。我通过以下方式解决了我的问题:
`info = []
time.sleep(2)
htmllist = driver.find_element_by_class_name("rewards-contents")
items = htmllist.find_elements_by_css_selector(".kas-count")
for item in items:
info.append(item.text)
print(item.text)
print(info)`