简体   繁体   中英

Beautiful Soup Grabbing next element

I am trying to pull the election electoral votes to check when it updates. But the hard part is that all the classes change on every refresh. I want to search for the text Trump and then find the next element which is the count.

I can find the element, by searching for the string Trump :

import requests
import re
from bs4 import BeautifulSoup
url = "https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=who+is+winning+the+presidential+election&eob=enn/p//1/0///////////"
r = requests.get(url)
soup = BeautifulSoup(r.content)
elm = soup.find(text='Trump')
print elm.text

I found the Trump element, with lm = soup.find(text='Trump') , but I don't know how to grab the next element after that one.

Your current code is looking for an exact match of a node with that text. Try this:

soup.body.findAll(text=re.compile('Trump'))
> ["Donald Trump is US president-elect in 'America's Brexit' as Hillary Clinton concedes election - live", 'Donald Trump ', 'Donald Trump wins presidential election, plunging US into uncertain future'... ]

You'll instead be looking for a regular expression containing the target text. You can refine the regular expression you're looking for, for example:

b.body.findAll(text=re.compile('Trump wins .+? uncertain future'))
> ['Donald Trump wins presidential election, plunging US into uncertain future']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM