Extract information in a span over multiple HTML documents - html

I have a problem in which I have around 700 html documents, each containing one letter contained in a span, all in given the same class.
is there a way to get out all the letters and join them together? Maybe using BeautifulSoup or other methods?

Sure there is. Try something like this:
import os
from BeautifulSoup import BeautifulSoup
letter_list = []
for file in os.listdir('path/to/dir'):
with open('path/to/file', 'r') as html_file:
html = ' '.join(str(x) for x in list(html_file)) # Combines each row in file into a single string
soup = BeautifulSoup(html)
letter = soup('span',{'class':'someclass'})[0].contents[0]
letter_list.append(letter)
my_string = ''.join(str(x) for x in letter_list)
This will iterate over the directory, open each html file and parse the string. The extracted letter is appended to a list and joined once all of the files have been parsed.

Related

Python: Creating PDF from PNG images and CSV tables using reportlab

I am trying to create a PDF document using a series of PDF images and a series of CSV tables using the python package reportlab. The tables are giving me a little bit of grief.
This is my code so far:
import os
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate
from reportlab.pdfgen.canvas import Canvas
from reportlab.platypus import *
from reportlab.platypus.tables import Table
from PIL import Image
from matplotlib.backends.backend_pdf import PdfPages
# Set the path to the folder containing the images and tables
folder_path = 'Files'
# Create a new PDF document
pdf_filename = 'testassessment.pdf'
canvas = Canvas(pdf_filename)
# Iterate through the files in the folder
for file in os.listdir(folder_path):
file_path = os.path.join(folder_path, file)
# If the file is an image, draw it on the PDF
if file.endswith('.png'):
canvas.drawImage(file_path, 105, 148.5, width=450, height=400)
canvas.showPage() #ends page
# If the file is a table, draw it on the PDF
elif file.endswith('.csv'):
df = pd.read_csv(file_path)
table = df.to_html()
canvas.drawString(10, 10, table)
canvas.showPage()
# Save the PDF
canvas.save()
The tables are not working. When I use .drawString it ends up looking like this:
Does anyone know how I can get the table to be properly inserted into the PDF?
According to the reportlab docs, page 14, "The draw string methods draw single lines of text on the canvas.". You might want to have a look at "The text object methods" on the same page.
You might want to consider using PyMuPDF with Stories it allows for more flexibility of layout from a data input. For an example of something very similar to what you are trying to achieve see: https://pymupdf.readthedocs.io/en/latest/recipes-stories.html#how-to-display-a-list-from-json-data

Convert Json String in Text file to Json file with Python 3

I have gathered around 5000 tweets using Twitter API but mistakenly wrote them into a .txt. I need them to be in .json format instead. I tried several solutions from simply changing the file format from txt to json to 3 hours worth of stackoverflow answers such as this:
import json
f = open("tweets.txt", "r")
content = f.read()
#print(content)
text_file = open("tweets4.json", "w")
text_file.write(content)
text_file.close()
But even this opened like a text string. I also tried to use json.dump() but since the string is already in Json format, it did double encoding and it was full of "\
In short, it looks like this:
Json string in text format
But should look like this (I re ran the code and saved new tweets to a json):
Json format

Scrape for Absolute URL with html.parse and remove duplicates

I am trying to make sure that the relative links are saved as absolute links into this CSV. (URL parse) I am also trying to remove duplicates, which is why I created the variable "ddupe".
I keep getting all the relative URLs saved when I open the csv in the desktop.
Can someone please help me figure this out? I thought about calling the "set" just like this page: How do you remove duplicates from a list whilst preserving order?
#Importing the request library to make HTTP requests
#Importing the bs4 library to extract / parse html and xml files
#utlize urlparse to change relative URL to absolute URL
#import csv (built in package) to read / write to Microsoft Excel
from bs4 import BeautifulSoup
import requests
from urllib.parse import urlparse
import csv
#create the page variable
#associate page to request to obtain the information from raw_html
#store the html information in a text
page = requests.get('https://www.census.gov/programs-surveys/popest.html')
parsed = urlparse(page)
raw_html = page.text # declare the raw_html variable
soup = BeautifulSoup(raw_html, 'html.parser') # parse the html
#remove duplicate htmls
ddupe = open(‘page.text’, ‘r’).readlines()
ddupe_set = set(ddupe)
out = open(‘page.text’, ‘w’)
for ddupe in ddupe_set:
out.write(ddupe)
T = [["US Census Bureau Links"]] #Title
#Finds all the links
links = map(lambda link: link['href'], soup.find_all('a', href=True))
with open("US_Census_Bureau_links.csv","w",newline="") as f:
cw=csv.writer(f, quoting=csv.QUOTE_ALL) #Create a file handle for csv writer
cw.writerows(T) #Creates the Title
for link in links: #Parses the links in the csv
cw.writerow([link])
f.close() #closes the program
The function you're looking for is urljoin, not urlparse (both from the same package urllib.parse). It should be used somewhere after this line:
links = map(lambda link: link['href'], soup.find_all('a', href=True))
Use a list comprehension or map + lambda like you did here to join the relative URLs with base paths.

scraping from multiple url

import requests
from bs4 import BeautifulSoup
import pandas as pd
#scraping data
page=requests.get('https://www.sec.gov/Archives/edgar/data/11860/0000011860-00-000025.txt')
soup=BeautifulSoup(page.content,'html.parser')
data_1=list(soup.children)[8]
main_data=list(data_1.children)[1].get_text()
#number of words
num=len(main_data.split())
this is my successful code to calculate total number of words from a single URL. now the challenge is to calculate number of words from a csv file which has got 500 urls in a column. i tried a lot but failed.
For parsing csv, there's the csv library, so you'd simply need:
import csv
with open('yourfile.csv', 'rb') as csvfile:
reader = csv.reader(csvfile) # add delimiter ='',quotechar ='' depending on csv structure
for URL in reader:
page = requests.get(URL)
#the rest of what you want to do with the content of URL
You could put your current code into a function and then call it for each parsed URL.

Extracting text from plain HTML and write to new file

I'm extracting a certain part of a HTML document (to be fair: basis for this is an iXBRL document which means I do have a lot of written formatting code inside) and write my output, the original file without the extracted part, to a .txt file. My aim is to measure the difference in document size (how much KB of the original document refers to the extracted part). As far as I know there shouldn't be any difference in HTML to text format, so my difference should be reliable although I am comparing two different document formats. My code so far is:
import glob
import os
import contextlib
import re
#contextlib.contextmanager
def stdout2file(fname):
import sys
f = open(fname, 'w')
sys.stdout = f
yield
sys.stdout = sys.__stdout__
f.close()
def extractor():
os.chdir(r"F:\Test")
with stdout2file("FileShortened.txt"):
for file in glob.iglob('*.html', recursive=True):
with open(file) as f:
contents = f.read()
extract = re.compile(r'(This is the beginning of).*?Until the End', re.I | re.S)
cut = extract.sub('', contents)
print(file.split(os.path.sep)[-1], end="| ")
print(cut, end="\n")
extractor()
Note: I am NOT using BS4 or lxml because I am not only interested in HTML text but actually in ALL lines between my start and end-RegEx incl. all formatting code lines.
My code is working without problems, however as I have a lot of files my FileShortened.txt document is quickly going to be massive in size. My problem is not with the file or the extraction, but with redirecting my output to various txt-file. For now, I am getting everything into one file, what I would need is some kind of a "for each file searched, create new txt-file with the same name as the original document" condition (arcpy module?!)?
Somehting like:
File1.html --> File1Short.txt
File2.html --> File2Short.txt
...
Is there an easy way (without changing my code too much) to invert my code in the sense of printing the "RegEx Match" to a new .txt file instead of "everything except my RegEx match"?
Any help appreciated!
Ok, I figured it out.
Final Code is:
import glob
import os
import re
from os import path
def extractor():
os.chdir(r"F:\Test") # the directory containing my html
for file in glob.glob("*.html"): # iterates over all files in the directory ending in .html
with open(file) as f, open((file.rsplit(".", 1)[0]) + ".txt", "w") as out:
contents = f.read()
extract = re.compile(r'Start.*?End', re.I | re.S)
cut = extract.sub('', contents)
out.write(cut)
out.close()
extractor()