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

Categories

Assume the following:

<td title="I want this title" role="gridcell"><a onclick="open" href="#">TEXT</a></td>

Now, I've successfully found respectively the table and individual rows using:

for rows in soup.find_all(['tr']):
    for cells in rows.find_all(['td']):

By printing cells I can see I've found the correct rows, but I'm really not sure how to take the title attribute and save it as a string? I've attempted to use temp = soup.find('td')['title'], but I'm getting errors doing this, so evidently I'm doing something wrong.

Any suggestions would be much appreciated!

See Question&Answers more detail:os

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

1 Answer

To get an attribute of an element, you can treat an element as a dictionary (reference):

soup.find('tag_name')['attribute_name']

And, in your case:

for tr in soup.find_all('tr'):
    for td in tr.find_all('td'):
        print(td.get('title', 'No title attribute'))

Note that I've used .get() method to avoid failing on td elements with no title attribute.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...