Как получить местоположение из профиля пользователя Twitter с помощью Beautiful Soup4? - PullRequest
1 голос
/ 17 июня 2020

Итак, я пытаюсь получить текст местоположения в профиле данной учетной записи Twitter

handles = ['IndieWire' , 'AFP', 'UN']

for x in handles:
    url= "https://twitter.com/" + x
    try:
        html = req.get(url)
    except Exception as e:
        print(f"Failed to fetch page for url {url} due to: {e}")
        continue
    soup = BeautifulSoup(html.text,'html.parser')
    try:
        label = soup.find('span',{'class':"ProfileHeaderCard-locationText"})
        label_formatted = label.string.lstrip()
        label_formatted = label_formatted.rstrip()
        if label_formatted != "":
            location_list.append(label_formatted)
            print(x + ' : ' + label_formatted)
        else:
            location_list.append(label_formatted)
            print(x + ' : ' + 'Not found')
    except AttributeError:
        try:
            label2 = soup.findAll('span',{"class":"ProfileHeaderCard-locationText"})[0].get_text()
            label2 = str(label2)
            label2_formatted = label2.lstrip()
            label2_formatted = label2_formatted.rstrip()
            location_list.append(label_formatted)
            print(x + ' : ' + label2_formatted)
        except:
            print(x + ' : ' + 'Not found')
    except:
            print(x + ' : ' + 'Not found')

Этот код работал, когда я использовал его несколько месяцев go. Я немного изменил его сейчас, после проверки источника страницы Twitter, но я все еще не могу получить местоположения. Надеюсь, ты сможешь помочь

1 Ответ

2 голосов
/ 17 июня 2020

Используйте мобильную версию Twitter для определения местоположения.

Например:

import requests
from bs4 import BeautifulSoup


handles = ['IndieWire' , 'AFP', 'UN']

ref = 'https://twitter.com/{h}'
headers = {'Referer': '',}
url = 'https://mobile.twitter.com/i/nojs_router?path=/{h}'

for h in handles:
    headers['Referer'] = ref.format(h=h)
    soup = BeautifulSoup( requests.post(url.format(h=h), headers=headers).content, 'html.parser' )
    loc = soup.select_one('.location')
    if loc:
        print(h, loc.text)
    else:
        print(h, 'Not Found')

Распечатывает:

IndieWire New York, NY
AFP France
UN New York, NY
...