Q
Q
Qvint012020-02-02 22:26:45
Python
Qvint01, 2020-02-02 22:26:45

How to create an exception in search?

Greetings, sometimes an error occurs in the code, and to be more specific, in the parser (it parses the url of a random photo from Google
)

.

import requests
from json import loads
from bs4 import BeautifulSoup
from random import choice

s = requests.session()
s.headers.update({'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:69.0) Gecko/20100101 Firefox/69.0'})
 
r = s.get('https://www.google.ru/search?q=мем&tbm=isch')
 
soup = BeautifulSoup(r.text, "html.parser")

elems = soup.findAll(attrs={'class': 'rg_meta notranslate'})
print(loads(choice(elems).text)['ou'])


Thanks in advance.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Pashenka, 2020-02-03
@Qvint01

import re

def getImg( imgURL ):
    pattern = re.compile(r'^.*\.(jp(e)?g|png)$')
    
    if bool( re.match(pattern, imgURL) ):
        return imgURL
    else:
        return getImg( loads(choice(elems).text)['ou'] )

print( getImg( loads(choice(elems).text)['ou'] ) )

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question