Python регулярные выражения найти все ссылки

Регулярные выражения. Парсинг html

Есть задача вытащить ссылки из html-файла. Первая мысль: «Регулярные выражения, настало ваше время». До этого момента с ними не сталкивался. Решил разобраться. Вот пробую по гугловским статьям. В итоге по задаче:

— есть html-код (в моем случае такой):

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
 html> head> title>Example Domain/title> meta charset="utf-8" /> meta http-equiv="Content-type" content="text/html; charset=utf-8" /> meta name="viewport" content="width=device-width, initial-scale=1" /> style type="text/css"> body < background-color: #f0f0f2; margin: 0; padding: 0; font-family: "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif; >div < width: 600px; margin: 5em auto; padding: 50px; background-color: #fff; border-radius: 1em; >a:link, a:visited < color: #38488f; text-decoration: none; >@media (max-width: 700px) < body < background-color: #fff; >div < width: auto; margin: 0 auto; border-radius: 0; padding: 1em; >> /style> /head> body> div> h1>Example Domain/h1> p>This domain is established to be used for illustrative examples in documents. You may use this domain in examples without prior coordination or asking for permission./p> p>a href="http://www.iana.org/domains/example">More information. /a>/p> /div> /body> /html>
#reg ex pattern = '\S*">' result = re.findall(pattern, string) # string - считанный код HTML print (result)

Вроде все хорошо, но в результате получаю ссылку (она одна, для тех, кто не глядел в html) вместе с «служебной информацией» . «>, а по задаче нужно получить именно ссылки. Это конечно можно реализовать функциями для работы с обычными строками (обрезать куски до и после кавычек), но хотелось бы узнать, как получить такой результат регулярными выражениями.

Читайте также:  Javascript all elements on page

Источник

URL regex Python

URL regular expressions can be used to verify if a string has a valid URL format as well as to extract an URL from a string.

URL regex that starts with HTTP or HTTPS

HTTP and HTTPS URLs that start with protocol can be validated using the following regular expression

Enter a text in the input above to see the result

 

URL regex that doesn’t start with HTTP or HTTPS

The regular expression to validate URL without protocol is very similar:

Enter a text in the input above to see the result

 

Enter a text in the input above to see the result

Notes on URL validation

The above-mentioned regular expressions only cover the most commonly used types of URLs with domain names. If you have some more complex cases you might need a different solution.

Create an internal tool with UI Bakery

Discover UI Bakery – an intuitive visual internal tools builder.

Источник

Используя регулярные выражения извлечь из текста html-файла все ссылки

Извлеките из текста html-файла все ссылки (всё, что содержится в шаблоне
)*
* Для работы с html запросами используйте библиотеку requests.
Для установки библиотеки на домашнем компьютере используйте команду
pip install requests, набранную в командной строке. Библиотека содержит
следующие основные методы:
GET — получение ресурса
POST — создание ресурса
PUT — обновление ресурса
DELETE — удаление ресурса
Начало программы 2 может выглядеть следующим образом:

import requests import re st1=input('введите адрес сайта ') res=requests.get(st1) s=res.text print(s)

Для группировки строк используйте круглые скобки. Подгруппы нумеруются
слева направо, от 1 и далее. Группы могут быть вложенными; для того, чтобы
определить число вложений, просто подсчитываем слева направо символы
открывающей скобки:

>>> p = re.compile('(a(b)c)d') >>> m = p.match('abcd') >>> m.group(0) 'abcd' >>> m.group(1) 'abc' >>> m.group(2) 'b'

group() может принять одновременно несколько номеров групп в одном
запросе, и будет возвращен кортеж, содержащий значения для соответствующих
групп:

Используя регулярные выражения, вытащить из текста все, что начинается с [ и заканчивается ]
Есть некий текст, из него надо вытащить все что начинается с . Использую модуль regexpr, но что то.

Регулярные выражения. Извлечь из html текст между двумя тегами
Ломаю голову с регулярными выражениями, не получается корректно решить простую задачу: Нужно.

Регулярные выражения: извлечь из текста цены в разной валюте
Создать программу: Есть текст со списками цен. Извлечь из него цены в USD, RUR, EU. – пример.

Регулярные выражения. Извлечь из текста цены в USD, RUR, EU.
Есть текст со списками цен. Извлечь из него цены в USD, RUR, EU. Примеры правильных выражений.

Эксперт Python

Эксперт PythonЭксперт Java

import re import requests text = requests.get('https://python-scripts.com/requests').text print(*re.findall(r'(?, text), sep='\n')
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
https://python-scripts.com/ https://python-scripts.com/install-python https://python-scripts.com/pycharm-download https://python-scripts.com/tkinter https://python-scripts.com/forum https://python-scripts.com/books https://python-scripts.com/beautifulsoup-html-parsing https://ru.wikipedia.org/wiki/HTTP https://python-scripts.com/virtualenv https://ru.wikipedia.org/wiki/HTTP#Методы https://developer.github.com/v3/#root-endpoint https://python-scripts.com/try-except-finally https://ru.wikipedia.org/wiki/Список_кодов_состояния_HTTP https://python-scripts.com/f-strings https://python-scripts.com/string https://ru.wikipedia.org/wiki/UTF-8 https://ru.wikipedia.org/wiki/Набор_символов https://ru.wikipedia.org/wiki/Заголовки_HTTP https://python-scripts.com/lists-tuples-dictionaries#dict https://en.wikipedia.org/wiki/Query_string https://developer.github.com/v3/search/ https://httpbin.org https://developer.github.com/v3/users/#get-the-authenticated-user https://python-scripts.com/try-except-finally https://realpython.com/python-requests/ https://www.patreon.com/python_community https://python-scripts.com/category/decorators https://python-scripts.com/category/gui/tkinter-python https://python-scripts.com/category/gui/pycairo-tutorials-python https://python-scripts.com/install-python-3-8-linux

Источник

Python-сообщество

[RSS Feed]

  • Начало
  • » Python для экспертов
  • » Регулярные выражения re для поиска всех ссылок на странице

#1 Янв. 8, 2011 00:33:16

Регулярные выражения re для поиска всех ссылок на странице

Привет всем!
Хочу узнать какие регулярки применяются для поиска всех ссылок на странице?

Вот этот вариант не подходит

#2 Янв. 8, 2011 09:00:49

Регулярные выражения re для поиска всех ссылок на странице

И не подойдёт. Мне думается, что проще использовать регулярку для URL, а не выдёргивать всё из href'ов:

^(?#Protocol)(?:(?:ht|f)tp(?:s?)\:\/\/|~\/|\/)?(?#Username:Password)(?:\w+:\w+@)?(?#Subdomains)(?:(?:[-\w]+\.)+(?#TopLevel Domains)(?:com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum|travel|[a-z]))(?#Port)(. [\d])?(?#Directories)(?:(?:(?:\/(?:[-\w~!$+|.,=]|%[a-f\d])+)+|\/)+|\?|#)?(?#Query)(?:(?:\?(?:[-\w~!$+|.,*:]|%[a-f\d])+=?(?:[-\w~!$+|.,*:=]|%[a-f\d])*)(?:&(?:[-\w~!$+|.,*:]|%[a-f\d])+=?(?:[-\w~!$+|.,*:=]|%[a-f\d])*)*)*(?#Anchor)(?:#(?:[-\w~!$+|.,*:=]|%[a-f\d])*)?$

#3 Янв. 8, 2011 13:56:08

Регулярные выражения re для поиска всех ссылок на странице

Да это видимо подойдет для всех возможных ссылок в вебе
Но мне местами не понятно здесь такие вот обороты (?#Protocol) и (?#Username:Password) и тд

Мне нужно пропарсить ссылки с блогов
Например с таких http://pravda-vsay.ya.ru/#y5__id37

А при использовании этого RE ничего не ищется 🙂

#4 Янв. 15, 2011 11:04:38

Регулярные выражения re для поиска всех ссылок на странице

import urllib

from BeautifulSoup import BeautifulSoup


soup = BeautifulSoup(urllib.urlopen('http://www.google.com/'))

print [dict(a.attrs)['href'] for a in soup('a') if 'href' in dict(a.attrs)]

#5 Янв. 15, 2011 18:44:56

o7412369815963 От: Зарегистрирован: 2009-06-17 Сообщения: 1986 Репутация: 32 Профиль Отправить e-mail

Регулярные выражения re для поиска всех ссылок на странице

#6 Янв. 15, 2011 18:50:10

o7412369815963 От: Зарегистрирован: 2009-06-17 Сообщения: 1986 Репутация: 32 Профиль Отправить e-mail

Регулярные выражения re для поиска всех ссылок на странице

потому что этот ре для валидации емайлов, у него в начале и в конце для этогог спец.символы. вот отрезал - терь ищет

# coding: utf8

import re

r = ur'(?#Protocol)(?:(?:ht|f)tp(?:s?)\:\/\/|~\/|\/)?(?#Username:Password)(?:\w+:\w+@)?(?#Subdomains)(?:(?:[-\w]+\.)+(?#TopLevel Domains)(?:com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum|travel|[a-z]))(?#Port)(. [\d])?(?#Directories)(?:(?:(?:\/(?:[-\w~!$+|.,=]|%[a-f\d])+)+|\/)+|\?|#)?(?#Query)(?:(?:\?(?:[-\w~!$+|.,*:]|%[a-f\d])+=?(?:[-\w~!$+|.,*:=]|%[a-f\d])*)(?:&(?:[-\w~!$+|.,*:]|%[a-f\d])+=?(?:[-\w~!$+|.,*:=]|%[a-f\d])*)*)*(?#Anchor)(?:#(?:[-\w~!$+|.,*:=]|%[a-f\d])*)?'

txt = u"""hi world!
you url http://pravda-vsay.ya.ru/#y5__id37
and google.com
"""

print re.findall(r, txt, re.U)
[u'http://pravda-vsay.ya.ru/#y5__id37', u'google.com']

Источник

How to Extract URL from a string in Python?

Today we are going to learn how we can find and extract a URL of a website from a string in Python. We will be using the regular expression module of python. So if we have a string and we want to check if it contains a URL and if it contains one then we can extract it and print it.

First, we need to understand how to judge a URL presence. To judge that we will be using a regular expression that has all possible symbols combination/conditions that can constitute a URL.

This regular expression is going to help us to judge the presence of a URL.

#regular expression to find URL in string in python r"(?i)\b((?:https?://|www\d[.]|[a-z0-9.-]+[.][a-z]/)(?:[^\s()<>]+|(([^\s()<>]+|(([^\s()<>]+)))))+(?:(([^\s()<>]+|(([^\s()<>]+))))|[^\s`!()[]<>;:'\".,<>?«»“”‘’]))"

Then we will just parse our string with this regular expression and check the URL presence. So to do that we will be using findall() method/function from the regular expression module of python.

Code Example

#How to Extract URL from a string in Python? import re def URLsearch(stringinput): #regular expression regularex = r"(?i)\b((?:https?://|www\d[.]|[a-z0-9.-]+[.][a-z]/)(?:[^\s()<>]+|(([^\s()<>]+|(([^\s()<>]+)))))+(?:(([^\s()<>]+|(([^\s()<>]+))))|[^\s`!()[]<>;:'\".,<>?«»“”‘’]))" #finding the url in passed string urlsrc = re.findall(regularex,stringinput) #return the found website url return [url[0] for url in urlsrc] textcontent = 'text :a software website find contents related to technology https://devenum.com https://google.com,http://devenum.com' #using the above define function print("Urls found: ", URLsearch(textcontent))
Urls found: ['https://devenum.com', 'https://google.com,http://devenum.com']

Find URL in string of HTML format

In this code example we are searching the urls inside a HTML tags.We are using the above defines regular expression to find the same.

import re def URLsearch(stringinput): #regular expression regularex = regularex = r"(?i)\b((?:https?://|www\d[.]|[a-z0-9.-]+[.][a-z]/)(?:[^\s()<>]+|(([^\s()<>]+|(([^\s()<>]+)))))+(?:(([^\s()<>]+|(([^\s()<>]+))))|[^\s`!()[]<>;:'\".,<>?«»“”‘’]))" #finding the url in passed string urlsrc = re.findall(regularex,stringinput) #return the found website url return [url[0] for url in urlsrc] textcontent = '

Contents Python ExamplesEven More Examples

' #using the above define function print("Urls found: ", URLsearch(textcontent))
Urls found: ['https://www.google.com"', 'https://devenum.com"', 'http://www.devenum.com"']

Источник

Оцените статью