Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
289 views
in Technique[技术] by (71.8m points)

I can't get all the <a> tags in selenium python

I need to get all the text inside the <a> tags, but I can get only the text of the first <a> tag.

Here is my code:

table_page = driver2.find_elements_by_class_name('paging')
for tn in table_page: 
    num = tn.find_element_by_class_name('paper.page_link')
    print(num.text)

and this is the HTML code:

<div class="paging">
    <em class=" link_page" style="cursor:pointer"> 1 </em>
    <a class="paper page_link" href="javascript:" url="./detail_nbid" page_num="2">2</a>
    <a class="paper page_link" href="javascript:" url="./detail_nbid" page_num="3">3</a>
</div>

what I expected is 2, 3 but I get only 2.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you select by class name, then you can only specify a class name. This doesn't give you the required flexibility you need here.

Try selecting by CSS Selector.

Here, you are interested in a tags with the class's paper and page_link.

For example:

for a in driver.find_elements_by_css_selector('a.paper.page_link'):
    print(a.text)

Output:

2
3

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...