0

I'm working on an idea I had to see if I could find a selection of specific tags on a given website and hit this snag really early on. Below I'm trying to find within a given link's HTML document if there's the presence of something that matches, in this case, 'google-analytics'.

By going to the link, right clicking and viewing the source code there very clearly is something within the site's source code that exactly matches 'google-analytics' but the code below is still not returning something to indicate that is in fact true. Even if I add some condition to show false otherwise, it returns false.

I'm sure the fix is right under my nose but I'm really stuck on this right now. Below is the latest version I've been tinkering with. Previously I had tried simply making the x variable the string itself, x = 'google-analytics' and testing with the same for-loop.

import requests
from bs4 import BeautifulSoup
import re
import csv

URL = "https://www.python.org/"
page = requests.get(URL)
soup = BeautifulSoup(page.content, "html.parser")
x = soup.find("google-analytics")

#print(soup.prettify())
for line in soup:
    print(line)
    if x in soup:
        print('found')

1 Answer 1

1

The line x = soup.find("google-analytics") will search for tag <google-analytics>, which doesn't exist in your document - and returns None.

Instead, the string google-analytics is inside <script> tag, so you want to search inside each of these tags.

For example:

import requests
from bs4 import BeautifulSoup

URL = "https://www.python.org/"
page = requests.get(URL)
soup = BeautifulSoup(page.content, "html.parser")

for s in soup.select('script'):
    if s.string and 'google-analytics' in s.string:
        print('Found!')
        break
else:
    print('Not Found!')

Prints:

Found!
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.