Fix "my ip" search regression

Removes dependency on class names for creating the "my ip" info card in
the results list for searches pertaining to the user's public IP.

Adds test to prevent this from happening again.

Note to anyone reading this and looking to contribute: please avoid
using hardcoded class names at all costs. This approach of
creating/removing content just results in issues if/when Google decides
to introduce/remove class names from the result page.

Fixes #657
main
Ben Busby 2022-02-14 11:40:11 -07:00
parent b2c048af92
commit d33e8241dc
No known key found for this signature in database
GPG Key ID: B9B7231E01D924A1
2 changed files with 26 additions and 23 deletions

View File

@ -198,33 +198,26 @@ def add_ip_card(html_soup: BeautifulSoup, ip: str) -> BeautifulSoup:
BeautifulSoup BeautifulSoup
""" """
if (not html_soup.select_one(".EY24We") # HTML IP card tag
and html_soup.select_one(".OXXup").get_text().lower() == "all"): ip_tag = html_soup.new_tag('div')
# HTML IP card tag ip_tag['class'] = 'ZINbbc xpd O9g5cc uUPGi'
ip_tag = html_soup.new_tag("div")
ip_tag["class"] = "ZINbbc xpd O9g5cc uUPGi"
# For IP Address html tag # For IP Address html tag
ip_address = html_soup.new_tag("div") ip_address = html_soup.new_tag('div')
ip_address["class"] = "kCrYT ip-address-div" ip_address['class'] = 'kCrYT ip-address-div'
ip_address.string = ip ip_address.string = ip
# Text below the IP address # Text below the IP address
ip_text = html_soup.new_tag("div") ip_text = html_soup.new_tag('div')
ip_text.string = "Your public IP address" ip_text.string = 'Your public IP address'
ip_text["class"] = "kCrYT ip-text-div" ip_text['class'] = 'kCrYT ip-text-div'
# Adding all the above html tags to the IP card # Adding all the above html tags to the IP card
ip_tag.append(ip_address) ip_tag.append(ip_address)
ip_tag.append(ip_text) ip_tag.append(ip_text)
# Finding the element before which the IP card would be placed # Insert the element at the top of the result list
f_link = html_soup.select_one(".BNeawe.vvjwJb.AP7Wnd") html_soup.select_one('#main').insert_before(ip_tag)
ref_element = f_link.find_parent(class_="ZINbbc xpd O9g5cc" +
" uUPGi")
# Inserting the element
ref_element.insert_before(ip_tag)
return html_soup return html_soup

View File

@ -89,6 +89,16 @@ def test_block_results(client):
assert result_site not in 'pinterest.com' assert result_site not in 'pinterest.com'
def test_view_my_ip(client):
rv = client.post(f'/{Endpoint.search}', data=dict(q='my ip address'))
assert rv._status_code == 200
# Pretty weak test, but better than nothing
str_data = str(rv.data)
assert 'Your public IP address' in str_data
assert '127.0.0.1' in str_data
def test_recent_results(client): def test_recent_results(client):
times = { times = {
'past year': 365, 'past year': 365,