Соскоб в сети с помощью bs4: при добавлении результатов в csv отображаются только два последних значения - PullRequest
0 голосов
/ 18 февраля 2019

Я новичок в Python e BS4.Я прочитал другие посты в переполнении стека, но не могу заставить его работать!Код, который я использую, адаптирован из кода, используемого в школе.Я пытаюсь очистить следующий веб-сайт: https://boards.euw.leagueoflegends.com/en/search?query=improve с BS4 и python 3.

Я получаю всю необходимую информацию (имя пользователя, сервер, ссылка, комментарии ..), однако при добавленииданные в файл CSV, я получаю разные результаты:

1) Для ссылки, имя пользователя, тема, вопрос и т. д. Я получаю разные результаты для каждой строки, как ожидалось

2) для комментариев ипредставления Я получаю только последние два значения, которые повторяются

def get_songs(url):

    index_page = BeautifulSoup(load_page(url), 'lxml') # Parse the page
    items = index_page.find(id='search-results') # Get the list on from the webpage
    if not items: # If the webpage does not contain the list, we should exit
        print('Something went wrong!', file=sys.stderr)
        sys.exit()
    data = list()

    for row in items.find_all(class_='title'):
        links = row.find_all('a', {"class": "title-link",}) 
        for link in links: 
            urls='https://boards.euw.leagueoflegends.com'+link.get('href')
        #print(urls)

        username = row.find(class_='username').text.strip()
        question = row.find(class_='title-span').text.strip()
        sentence = row.find('span')['title']
        serverzone = row.find(class_='realm').text.strip()
        #print(serverzone)
        topic = row.find('div', {'class':'discussion-footer byline opaque'}).find_all('a')[1].text.strip()
        #print(topic)
        date=row.find(class_='timeago').get('title')
        #print(date)

        #To access the comments and views, a request to the server must be made

        r = requests.get('https://boards.euw.leagueoflegends.com/en/search?query=improve')
        #print(r)
        content=r.text
        #print(content)
        parser = BeautifulSoup(content,'lxml') # Parse the page
        #find the views
        viewclass = parser.find_all(class_='view-counts byline')
        for region in viewclass:
            views = region.find('span', {'class' : 'number opaque'}).get('data-short-number')
            print(views)
        #find the comments
        commentclass = parser.find_all(class_='num-comments byline')
        for region2 in commentclass:
            comments = region2.find('span', {'class' : 'number opaque'}).get('data-short-number')
            print(comments)

        # Store the data in a dictionary, and add that to our list
        data.append({
                    'number_of_comments':comments,
                    'link': urls,
                    'username': username,
                     'topic':topic,
                     'question':question,
                     'sentence':sentence,
                     'server':serverzone,
                     'date':date,
                     'number_of_views':views
                    })
    return data

При печати комментариев и представлений, которые являются результатом двух циклов, я вижу все из них, однако при чтении файла CSV только последние два значенияпредставления и столбцы показаны ..

Например, представления: 506 641 ... до двух последних значений 842 и 544, файл csv просто несколько раз печатает 842 544 Я думаю, что есть проблема с циклами,Я перепробовал много вариантов, но не смог заставить его работать

Не могли бы вы мне помочь?

1 Ответ

0 голосов
/ 19 февраля 2019

Прежде всего, вам не нужен второй запрос к серверу для доступа к комментариям и просмотра.Все, что вам нужно, это изменить указатель для вашей row переменной:

for row in items.find_all(class_='discussion-list-item'):

Так что теперь доступен доступ к просмотрам и комментариям

views = row.find(class_='view-counts byline').find('span', {'class' : 'number opaque'}).get('data-short-number')
comments = row.find(class_='num-comments byline').find('span', {'class' : 'number opaque'}).get('data-short-number')

Вот пример кода:

def load_page(url):
    r = requests.get(url)
    return r.text

def get_songs(url):

    index_page = BeautifulSoup(load_page(url), 'lxml') # Parse the page
    items = index_page.find(id='search-results') # Get the list on from the webpage
    if not items: # If the webpage does not contain the list, we should exit
        print('Something went wrong!', file=sys.stderr)
        sys.exit()
    data = list()

    for row in items.find_all(class_='discussion-list-item'):
        links = row.find_all('a', {"class": "title-link",})
        for link in links:
            urls='https://boards.euw.leagueoflegends.com'+link.get('href')
        #print(urls)

        username = row.find(class_='username').text.strip()
        question = row.find(class_='title-span').text.strip()
        sentence = row.find('span')['title']
        serverzone = row.find(class_='realm').text.strip()
        #print(serverzone)
        topic = row.find('div', {'class':'discussion-footer byline opaque'}).find_all('a')[1].text.strip()
        #print(topic)
        date=row.find(class_='timeago').get('title')
        #print(date)
        views = row.find(class_='view-counts byline').find('span', {'class' : 'number opaque'}).get('data-short-number')
        comments = row.find(class_='num-comments byline').find('span', {'class' : 'number opaque'}).get('data-short-number')
        # Store the data in a dictionary, and add that to our list
        data.append({
                    'number_of_comments':comments,
                    'link': urls,
                    'username': username,
                     'topic':topic,
                     'question':question,
                     'sentence':sentence,
                     'server':serverzone,
                     'date':date,
                     'number_of_views':views
                    })
    return data

data = get_songs('https://boards.euw.leagueoflegends.com/en/search?query=improve')
print(data)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...