I'm working on a project using Python(3.7) and BeautifulSoup(4) to implement a scraping solution.
Note: I have searched to find a solution to my problem, but I couldn't find any solution because it's different from what usually we need for scraping. So, that's why, don't mark this as duplicate, please!
This project has two parts:
- We have grabbed the Google search results URLs (first 5 for example) on the base of a search term.
- Then, we have to scrape those search results' URLs to grab the search term's related information from those pages, so we don't know the actual classes/tags of those results' pages.
So, how we can grab the search term's relevant information from web pages without knowing the actual tags/classes?
Here's what I have done so far:
soup = BeautifulSoup(driver.page_source, 'lxml')
result_div = soup.find_all('div', attrs={'class': 'g'})
links = []
titles = []
descriptions = []
for r in result_div:
# Checks if each element is present, else, raise exception
try:
link = r.find('a', href=True)
title = None
title = r.find('h3')
if isinstance(title, Tag):
title = title.get_text()
description = None
description = r.find('span', attrs={'class': 'st'})
if isinstance(description, Tag):
description = description.get_text()
# Check to make sure everything is present before appending
if link != '' and title != '' and description != '':
links.append(link['href'])
titles.append(title)
descriptions.append(description)
# Next loop if one element is not present
except Exception as e:
print(e)
continue