Интернет - это океан данных. К сожалению, важные данные неструктурированы или труднодоступны для пользователя. Иногда API-интерфейсы доступны, но не для всех необходимых нам данных. Мы можем преодолеть это, извлекая данные из Интернета и используя их любым структурным способом, каким захотим. Искусство сбора данных из Интернета известно как веб-скрапинг.
В этом посте я покажу вам, как я отказался от HackerNews и извлек ссылки на статьи менее чем в 15 строк кода.
Лом с питоном
Посмотрите на код, написанный ниже -
import requests from bs4 import BeautifulSoup url="https://news.ycombinator.com" #url to scrap #if you are behind any proxy server proxies={"http":None,"https":None, "ftp":None} r = requests.get(url, proxies=proxies) soup = BeautifulSoup(r.content, "html.parser") file = open("news_link.dat", "w") for link in soup.find_all("a", class_="storylink"): s=link.text+"\n"+link.get("href")+"\n\n" file.write(s) file.close()
Я использовал запросы и BeautifulSoup для python на слом. В первых двух строках я импортировал эти две библиотеки в свой код.
Вы можете установить их с помощью pip (pip - это система управления пакетами, используемая для установки и управления программными пакетами, написанными на Python).
pip install requests #to install requests #to install BeautifulSoup apt-get install python-bs4 (for Python 2) apt-get install python3-bs4 (for Python 3) pip install beautifulsoup4
URL для записки
url="https://news.ycombinator.com"
Чтобы открыть URL-адрес в моем скрипте Python
r = request.get(url, proxies=proxy) # request.get() method opens url and return a reference to html content of page, In my case it is r # if trying to open this url through proxy server use python dict to pass proxies as second argument in requests.get() method in the format proxy = {"http":"http://username:password@proxyserver:port", "https":"https://username:password@proxyserver:port"}
Загрузка HTML в BeautifulSoup
BeautifulSoup предоставляет нам различные методы для извлечения данных из содержимого html.
soup = BeautifulSoup(r.content, "html.parser") #this line of code load our html in BeautifulSoup and returns a reference, In my case it is soup #r.content contains html data in text format #html.parser is a html parser which is used to parse html #Parsing is to resolve (a sentence) into its component parts and describe their syntactic roles.
Время найти наши ссылки
file = open("news_link.dat", "w") for link in soup.find_all("a", class_="storylink"): s=link.text+"\n"+link.get("href")+"\n\n" file.write(s) file.close() # open() method opens a file with name "news_links.dat" #for loop to iterate through list of links ans save them to file news_links.dat #soup.find_all("s", class_="storylink") methd return a list of all "a"(anchor) tags with class "storylink"
Я написал менее 15 строк кода, который удалит веб-страницу и сохранит все ссылки в текстовый файл.
Вывод
Можно использовать запросы и BeautifulSoup для python, чтобы избавиться от Интернета и использовать эти данные любым возможным структурным способом. Но помните, что на веб-сайтах есть файл robots.txt, который определяет некоторые правила (не отправлять слишком много запросов часто, какие URL можно удалять, а какие нет, и т. Д.), Которым должен следовать ваш парсер.
Счастливое кодирование