Issue
I want to extract the values of the "id" attribute from a list of table rows like this one:
<tr id="8LVPCRJGR" role="row" class="odd">
, via BeautifulSoup4. In the case of this example tag, I want the "8LVPCRJGR" part.
I tried this block of code (yes, I did import bs4 and requests modules):
url = "https://brawlify.com/stats/club/V8GVVR0R"
result = requests.get(url).text
doc = BeautifulSoup(result, "html.parser")
tag = doc.find_all('tr')
attribute = tag['id']
print(attribute)
It's supposed to print out a list with all the values in it, but nothing prints. The console is blank.
What am I doing wrong here?
Solution
Few issues. First, tag is list of elements, specifically all the <tr>
tag elements. Secondly, not all the <tr>
tags have an 'id'
attribute.
So you need to put in some logic for that:
import requests
from bs4 import BeautifulSoup
url = "https://brawlify.com/stats/club/V8GVVR0R"
result = requests.get(url).text
doc = BeautifulSoup(result, "html.parser")
tag = doc.find_all('tr')
attribute = [x['id'] for x in tag if 'id' in x.attrs]
Output:
print(attribute)
['8LVPCRJGR', '29G9VJJC', '2YP08GUG8', 'UY8PVUPL', 'VV2RRRGG', '20RQQ08U9', 'VJ00J8Y8', '200PG2VLP', '28QV0RJVV', 'YRLPJ80J', 'PRLV99U89', '9QJLQGGU', '88UYYG0U', '9PG8RUVJ', 'YP9UQ8CQ', '9J8LRGQU2', '2LPGYQVV9', '8C8CJ0UJU', 'GUGJLLRG', '9Q0VCV2J', '2RVYVL8YL', 'JP0VGC2P', '280GY2R2C', '2PRLQPJJY', '8CGJGPYJ9', '89RYCVQJ0', '80GVU28CC', 'UV0CPU2Q', '9RGG9J08J', 'Y2PQ8090R']
Answered By - chitown88
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.