Запись нескольких файлов в качестве вывода при webscraping - python bs4 - PullRequest
0 голосов
/ 06 июля 2019

к предисловию - я новичок в Python, и мои навыки HTML - это уровень детского сада.

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

Мне удалось получить реальный код для извлечения кавычек (с помощью пользователей soem stackoverflow), но я теряюсь, как записывать эти кавычки в отдельные текстовые файлы для каждого кандидата.

Например, первая страница со всеми цитатами Джастина Амаша должна быть записана в файл: JustinAmash.txt.Вторая страница со всеми цитатами Майкла Беннета должна быть записана в MichaelBennet.txt (или что-то в этом виде).и так далее ... Есть ли способ сделать это?

Для справки, чтобы очистить страницы, работает следующий код:

import bs4
from urllib.request import Request,urlopen as uReq, HTTPError 
#Import HTTPError in order to avoid the links with no content/resource of interest
from bs4 import BeautifulSoup as soup_
import re
#define url of interest
my_url = 'http://archive.ontheissues.org/Free_Trade.htm'


def make_soup(url):
    # set up known browser user agent for the request to bypass HTMLError
    req=Request(url,headers={'User-Agent': 'Mozilla/5.0'})

    #opening up connection, grabbing the page
    uClient = uReq(req)
    page_html = uClient.read()
    uClient.close()

    #html is jumbled at the moment, so call html using soup function
    soup = soup_(page_html, "lxml") 
    return soup

# Test: print title of page
#soup.title

soup = make_soup(my_url)
tags = soup.findAll("a" , href=re.compile("javascript:pop\("))
#print(tags)

# open a text file and write it if it doesn't exist
file1 = open("Quotefile.txt","w")

# get list of all URLS
for links in tags:
    link = links.get('href')
    if "java" in link: 
        print("http://archive.ontheissues.org" + link[18:len(link)-3])
        main_url = "http://archive.ontheissues.org" + link[18:len(link)-3] 
        try:
            sub_soup = make_soup(main_url)
            content_collexn = sub_soup.body.contents #Splitting up the page into contents for iterative access 
            #text_data = [] #This list can be used to store data related to every person
            for item in content_collexn:
                #Accept an item if it belongs to the following classes
                if(type(item) == str):
                    print(item.get_text())
                elif(item.name == "h3"):
                    #Note that over here, every h3 tagged title has a string following it
                    print(item.get_text())   
                    #Hence, grab that string too
                    print(item.next_sibling) 
                elif(item.name in ["p", "ul", "ol"]):
                    print(item.get_text())

        except HTTPError: #Takes care of missing pages and related HTTP exception
            print("[INFO] Resource not found. Skipping to next link.")

        #print(text_data)

1 Ответ

0 голосов
/ 08 июля 2019

Вы можете сохранить эти текстовые данные в списке, который вы начали с text_data. Присоединитесь ко всем этим пунктам и затем запишите в файл:

Так что-то вроде:

import bs4
from urllib.request import Request,urlopen as uReq, HTTPError 
#Import HTTPError in order to avoid the links with no content/resource of interest
from bs4 import BeautifulSoup as soup_
import re
#define url of interest
my_url = 'http://archive.ontheissues.org/Free_Trade.htm'


def make_soup(url):
    # set up known browser user agent for the request to bypass HTMLError
    req=Request(url,headers={'User-Agent': 'Mozilla/5.0'})

    #opening up connection, grabbing the page
    uClient = uReq(req)
    page_html = uClient.read()
    uClient.close()

    #html is jumbled at the moment, so call html using soup function
    soup = soup_(page_html, "lxml") 
    return soup

# Test: print title of page
#soup.title

soup = make_soup(my_url)
tags = soup.findAll("a" , href=re.compile("javascript:pop\("))
#print(tags)

# open a text file and write it if it doesn't exist
#file1 = open("Quotefile.txt","w")

# get list of all URLS
candidates = []
for links in tags:

    link = links.get('href')
    if "java" in link: 
        #print("http://archive.ontheissues.org" + link[18:len(link)-3])
        main_url = "http://archive.ontheissues.org" + link[18:len(link)-3]
        candidate = link.split('/')[-1].split('_Free_Trade')[0]

        if candidate in candidates:
            continue
        else:
            candidates.append(candidate)

        try:
            sub_soup = make_soup(main_url)
            content_collexn = sub_soup.body.contents #Splitting up the page into contents for iterative access 
            text_data = [] #This list can be used to store data related to every person
            for item in content_collexn:
                #Accept an item if it belongs to the following classes
                if(type(item) == str):
                    #print(item.get_text())
                    text_data.append(item.get_text())
                elif(item.name == "h3"):
                    #Note that over here, every h3 tagged title has a string following it
                    #print(item.get_text()) 
                    text_data.append(item.get_text())
                    #Hence, grab that string too
                    #print(item.next_sibling) 
                    text_data.append(item.next_sibling)
                elif(item.name in ["p", "ul", "ol"]):
                    #print(item.get_text())
                    text_data.append(item.get_text())

        except HTTPError: #Takes care of missing pages and related HTTP exception
            print("[INFO] Resource not found. Skipping to next link.")
            candidates.remove(candidate)
            continue

        text_data = '\n'.join(text_data)
        with open("C:/%s.txt" %(candidate), "w") as text_file:
            text_file.write(text_data)
        print('Aquired: %s' %(candidate))
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...