BS4 get XML tag variables
<p>I am playing around with web scraping using bs4 and trying to get the title and color tag from this line of xml <code>&lt;graph gid="1" color="#000000" balloon_color="#000000" title="Approve"&gt;</code></p>

<p>The output result would be a dict something along the lines of <code>{'title':'approve', 'color':'#000000'}</code></p>

<p>The page where the xml is <a href="http://charts.realclearpolitics.com/charts/1044.xml" rel="nofollow">here</a></p>

<p>I've already written this function which is by no means efficient, but would like the titles of my dataframe to be the result of the <code>title</code> rather than a manually inputted value. So rather than <code>GID1</code> it would read <code>Approve</code> or <code>Obama</code> or whatever the result of title is. </p>

<pre><code>def rcp_poll_data(xml):
    soup=bs(xml,"xml")
    dates = soup.find('series')
    datesval = dates.findChildren(string=True)
    del datesval[-7:]
    obama = soup.find('graph', { "gid" : "1" })
    obamaval = obama.findChildren(string=True)
    romney = soup.find('graph', { "gid" : "2" })
    romneyval = romney.findChildren(string=True)
    result = pd.DataFrame({'date':pd.to_datetime(datesval), 'GID1':obamaval, 'GID2':romneyval})
    return result
</code></pre>

<p>I'm using bs4 and struggling to find the right terminology that would get me there. Are these tags i'm trying to isolate, or elements, or attributes?</p>

<p>This isn't a professional thing i'm just nurdling around for fun. So any help to get me slightly closer would be great. (i'm using python 3)</p>

<p>You just need to pull the <em>attributes</em> once you find the <em>graph node</em>:</p>

<pre><code>import requests
from bs4 import BeautifulSoup

soup = BeautifulSoup(requests.get("http://charts.realclearpolitics.com/charts/1044.xml").content,"xml")
g = soup.find("graph", gid="1")
data = {"title":g["title"], "color": g["color"]}
</code></pre>

<p>Which will give you:</p>

<pre><code>{'color': '#000000', 'title': 'Approve'}
</code></pre>

python xml python-3.x beautifulsoup