Ich habe versucht, eine HTML-Tabelle aus einer Ölproduktion SSRS-Feed online zu kratzen. Ich habe es geschafft, ein bisschen schöne Suppe/Python zu lernen, um zu dem Punkt zu kommen, an dem ich gerade bin, aber ich denke, ich brauche ein wenig Hilfe, um es fertig zu machen.Python Schöne Suppe Tabelle kratzen
Ziel ist es, die Tabelle zu scrapen, die alle getaggt ist und Json-Daten ausgeben. Ich habe eine Ausgabe im json-Format, aber für die 10 Header, aber es wiederholt den gleichen Datenzeilenzellenwert pro Header. Ich denke, die Iteration durch die Zellen, die den Headern zuzuordnen sind, ist das Problem. Ich bin mir sicher, dass es Sinn machen wird, wenn man rennt.
Jede Hilfe würde sehr geschätzt werden, versuchen zu erfahren, was ich falsch gemacht habe, denn das ist ziemlich neu für mich.
Prost
import json
from bs4 import BeautifulSoup
import urllib.request
import boto3
import botocore
#Url to scrape
url='http://factpages.npd.no/ReportServer?/FactPages/TableView/
field_production_monthly&rs:Command=Render&rc:Toolbar=
false&rc:Parameters=f&Top100=True&IpAddress=108.171.128.174&
CultureCode=en'
#Agent detail to prevent scraping bot detection
user_agent = 'Mozilla/5(Macintosh; Intel Mac OS X 10_9_3)
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47
Safari/537.36'
header = {'User-Agent': user_agent}
#Request url from list above, assign headers from criteria above
req = urllib.request.Request(url, headers = header)
#Open url from the previous request and assign
npddata = urllib.request.urlopen(req, timeout = 20)
#Start soup on url request data
soup = BeautifulSoup(npddata, 'html.parser')
# Scrape the html table variable from selected website
table = soup.find('table')
headers = {}
col_headers = soup.findAll('tr')[3].findAll('td')
for i in range(len(col_headers)):
headers[i] = col_headers[i].text.strip()
# print(json.dumps(headers, indent = 4))
cells = {}
rows = soup.findAll('td', {
'class': ['a61cl', 'a65cr', 'a69cr', 'a73cr', 'a77cr', 'a81cr', 'a85cr',
'a89cr', 'a93cr', 'a97cr']})
for row in rows[i]: #remove index!(###ISSUE COULD BE HERE####)
# findall function was original try (replace getText with FindAll to try)
cells = row.getText('div')
# Attempt to fix, can remove and go back to above
#for i in range(len(rows)): #cells[i] = rows[i].text.strip()
#print(cells)# print(json.dumps(cells, indent = 4))
#print(cells)# print(json.dumps(cells, indent = 4))
data = []
item = {}
for index in headers:
item[headers[index]] = cells#[index]
# if no getText on line 47 then.text() here### ISSUE COULD BE HERE####
data.append(item)
#print(data)
print(json.dumps(data, indent = 4))
# print(item)#
print(json.dumps(item, indent = 4))
Einrückung ist wichtig in Python, stellen Sie bitte sicher, dass Ihre Code-Beispiele den richtigen Einzug haben. – bgse