Web scraping w Pythonie.
Poniżej dwa przykłady Web Scraping'u z wykorzytaniem biblioteki BeautifulSoup. Programy przeszukują wskazane strony internetowe w poszukiwaniu zdefiniowanych atrybutów, następnie zapisują je do pliku.
Przykład pierwszy:
from bs4 import BeautifulSoup
import requests
import csv
page_to_scrap=requests.get("http://quotes.toscrape.com")
soup = BeautifulSoup(page_to_scrap.text, "html.parser")
quotes=soup.findAll("span", attrs={"class":"text"})
authors=soup.findAll("small", attrs={"class": "author"})
file=open("scraped_quotes.csv","w")
writer=csv.writer(file)
writer.writerow(["QUOTES","AUTHORS"])
for quote,author in zip(quotes,authors):
print(quote.text + " - " + author.text)
writer.writerow([quote.text, author.text])
file.close()
Przykład drugi:
from bs4 import BeautifulSoup
import requests
import csv
page_to_scrap=requests.get("http://neruo.pl")
soup = BeautifulSoup(page_to_scrap.text, "html.parser")
quotes=soup.findAll("h3")
authors=soup.findAll("h5")
file=open("neruo.csv","w")
writer=csv.writer(file)
writer.writerow(["Tytuły","Daty"])
h3_elementy=soup.find_all('h3')
for h3 in h3_elementy:
print(h3.text)
h5_elementy=soup.find_all('h5')
for h5 in h5_elementy:
print(h5.text)
for h3,h5 in zip(h3_elementy,h5_elementy):
print(h3.text + ' '+h5.text)
for h3,h5 in zip(h3_elementy,h5_elementy):
print(h3.text + " - " + h5.text)
writer.writerow([h3.text.encode('utf-8',errors='ignore'), h5.text.encode('utf-8',errors='ignore')])
file.close()
W celu zidentyfikowania interesującego nas elementu umieszcznego na stronie internetowej, posługujemy się poleceniem "inspekcji" w przeglądarce.
Przykład z wyszukiwaniem słów kluczowych:
from bs4 import BeautifulSoup
import requests
import csv
page_to_scrap=requests.get("http://neruo.pl")
soup = BeautifulSoup(page_to_scrap.text, "html.parser")
elements = soup.find_all(['h2','h3'])
keywords=['raspberry','pythonie'] # poszukiwanie tekstów zawierających słowa kluczowe
for keyword in keywords:
print(keyword)
results = soup.find_all(string=lambda text: keyword.lower() in text.lower())
for result in results:
parent = result.parent
print(parent.text)
if parent.name == 'a':
print(parent['href'])