Webscraping: сканирование страниц и хранение контента в DataFrame - PullRequest
0 голосов
/ 29 октября 2018

Следующий код можно использовать для воспроизведения задачи веб-очистки для трех приведенных примеров URL:

Код:

import pandas as pd
import requests
import urllib.request
from bs4 import BeautifulSoup

# Would otherwise load a csv file with 100+ urls into a DataFrame
# Example data:
links = {'url': ['https://www.apple.com/education/', 'https://www.apple.com/business/', 'https://www.apple.com/environment/']}
urls = pd.DataFrame(data=links)

def scrape_content(url):

    r = requests.get(url)
    html = r.content
    soup = BeautifulSoup(html,"lxml")

    # Get page title
    title = soup.find("meta",attrs={"property":"og:title"})["content"].strip()
    # Get content from paragraphs
    content = soup.find("div", {"class":"section-content"}).find_all('p')

    print(title)

    for p in content:
        p = p.get_text(strip=True)
        print(p)

Применить соскоб к каждому URL:

urls['url'].apply(scrape_content)

Из:

Education
Every child is born full of creativity. Nurturing it is one of the most important things educators do. Creativity makes your students better communicators and problem solvers. It prepares them to thrive in today’s world — and to shape tomorrow’s. For 40 years, Apple has helped teachers unleash the creative potential in every student. And today, we do that in more ways than ever. Not only with powerful products, but also with tools, inspiration, and curricula to help you create magical learning experiences.
Watch the keynote
Business
Apple products have always been designed for the way we work as much as for the way we live. Today they help employees to work more simply and productively, solve problems creatively, and collaborate with a shared purpose. And they’re all designed to work together beautifully. When people have access to iPhone, iPad, and Mac, they can do their best work and reimagine the future of their business.
Environment
We strive to create products that are the best in the world and the best for the world. And we continue to make progress toward our environmental priorities. Like powering all Apple facilities worldwide with 100% renewable energy. Creating the next innovation in recycling with Daisy, our newest disassembly robot. And leading the industry in making our materials safer for people and for the earth. In every product we make, in every innovation we create, our goal is to leave the planet better than we found it. Read the 2018 Progress Report

0    None
1    None
2    None
Name: url, dtype: object

Проблемы:

  1. Код в настоящее время выводит контент только для первого абзаца каждой страницы. Мне нравится получать данные для каждого p в данном селекторе.
  2. Для окончательных данных мне нужен фрейм данных, который содержит URL, заголовок и контент. Поэтому мне нравится знать, как я могу записать извлеченную информацию во фрейм данных.

Спасибо за вашу помощь.

1 Ответ

0 голосов
/ 29 октября 2018

Ваша проблема в этой строке:

content = soup.find("div", {"class":"section-content"}).find_all('p')

find_all() получает все теги <p>, но только в результатах .find() - что просто возвращает первый пример, который соответствует критериям. Таким образом, вы получаете все теги <p> в первом div.section_content. Не совсем понятно, какие критерии подходят для вашего случая использования, но если вам нужны все теги <p>, которые вы можете использовать:

content = soup.find_all('p')

Затем вы можете scrape_urls() объединить текст тега <p> и вернуть его вместе с заголовком:

content = '\r'.join([p.get_text(strip=True) for p in content])
return title, content

Вне функции вы можете построить фрейм данных:

url_list = urls['url'].tolist()
results = [scrape_url(url) for url in url_list]
title_list = [r[0] for r in results]
content_list = [r[1] for r in results]
df = pd.DataFrame({'url': url_list, 'title': title_list, 'content': content_list})
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...