Регулярное выражение Python для HTML, анализирующего (BeautifulSoup)

@ Метод использования скрытого контента: url () после использования тела Kristian, похоже, не работает в Firefox 48.0 (OS X).

Однако изменение «display: none»; к чему-то вроде:

body:after {
 position: absolute; overflow: hidden; left: -50000px;
 content: url(/path/to/picture-1.jpg) url(/path/to/picture-2.jpg);
}

... сделал трюк для меня. Возможно, Firefox не загрузит скрытые изображения, или, может быть, это связано с рендерингом (?).

11
задан eLRuLL 16 December 2017 в 23:06
поделиться

7 ответов

Для этого конкретного случая BeautifulSoup более трудно записать, чем regex, но это намного более устойчиво... Я просто способствую с примером BeautifulSoup, учитывая, что Вы уже знаете который regexp использовать :-)

from BeautifulSoup import BeautifulSoup

#Or retrieve it from the web, etc. 
html_data = open('/yourwebsite/page.html','r').read()

#Create the soup object from the HTML data
soup = BeautifulSoup(html_data)
fooId = soup.find('input',name='fooId',type='hidden') #Find the proper tag
value = fooId.attrs[2][1] #The value of the third attribute of the desired tag 
                          #or index it directly via fooId['value']
27
ответ дан 3 December 2019 в 00:48
поделиться
import re
reg = re.compile('<input type="hidden" name="([^"]*)" value="<id>" />')
value = reg.search(inputHTML).group(1)
print 'Value is', value
8
ответ дан 3 December 2019 в 00:48
поделиться

Я соглашаюсь с Vinko BeautifulSoup, способ пойти. Однако я предлагаю использовать fooId['value'] получить атрибут вместо того, чтобы полагаться на значение, являющееся третьим атрибутом.

from BeautifulSoup import BeautifulSoup
#Or retrieve it from the web, etc.
html_data = open('/yourwebsite/page.html','r').read()
#Create the soup object from the HTML data
soup = BeautifulSoup(html_data)
fooId = soup.find('input',name='fooId',type='hidden') #Find the proper tag
value = fooId['value'] #The value attribute
18
ответ дан 3 December 2019 в 00:48
поделиться

Парсинг является одной из тех областей, где Вы действительно не хотите к самокрутке, если можно избежать его, поскольку Вы будете упорно искать пограничные случаи, и ошибки в течение многих лет идут, прибывают

Я рекомендовал бы использовать BeautifulSoup. Это имеет очень хорошую репутацию и взгляды из документов как, он довольно прост в использовании.

5
ответ дан 3 December 2019 в 00:48
поделиться
/<input type="hidden" name="fooId" value="([\d-]+)" \/>/
0
ответ дан 3 December 2019 в 00:48
поделиться
/<input\s+type="hidden"\s+name="([A-Za-z0-9_]+)"\s+value="([A-Za-z0-9_\-]*)"\s*/>/

>>> import re
>>> s = '<input type="hidden" name="fooId" value="12-3456789-1111111111" />'
>>> re.match('<input\s+type="hidden"\s+name="([A-Za-z0-9_]+)"\s+value="([A-Za-z0-9_\-]*)"\s*/>', s).groups()
('fooId', '12-3456789-1111111111')
0
ответ дан 3 December 2019 в 00:48
поделиться

Pyparsing - хороший промежуточный шаг между BeautifulSoup и регулярным выражением. Он более надежен, чем просто регулярные выражения, поскольку его анализ HTML-тегов учитывает вариации регистра, пробелов, наличия / отсутствия / порядка атрибутов, но этот тип базового извлечения тегов проще, чем использование BS.

Ваш пример особенно прост, поскольку все, что вы ищете, находится в атрибутах открывающего тега «input». Вот пример pyparsing, показывающий несколько вариантов вашего входного тега, которые будут соответствовать регулярным выражениям, а также показывает, как НЕ сопоставлять тег, если он находится в комментарии:

html = """<html><body>
<input type="hidden" name="fooId" value="**[id is here]**" />
<blah>
<input name="fooId" type="hidden" value="**[id is here too]**" />
<input NAME="fooId" type="hidden" value="**[id is HERE too]**" />
<INPUT NAME="fooId" type="hidden" value="**[and id is even here TOO]**" />
<!--
<input type="hidden" name="fooId" value="**[don't report this id]**" />
-->
<foo>
</body></html>"""

from pyparsing import makeHTMLTags, withAttribute, htmlComment

# use makeHTMLTags to create tag expression - makeHTMLTags returns expressions for
# opening and closing tags, we're only interested in the opening tag
inputTag = makeHTMLTags("input")[0]

# only want input tags with special attributes
inputTag.setParseAction(withAttribute(type="hidden", name="fooId"))

# don't report tags that are commented out
inputTag.ignore(htmlComment)

# use searchString to skip through the input 
foundTags = inputTag.searchString(html)

# dump out first result to show all returned tags and attributes
print foundTags[0].dump()
print

# print out the value attribute for all matched tags
for inpTag in foundTags:
    print inpTag.value

Prints:

['input', ['type', 'hidden'], ['name', 'fooId'], ['value', '**[id is here]**'], True]
- empty: True
- name: fooId
- startInput: ['input', ['type', 'hidden'], ['name', 'fooId'], ['value', '**[id is here]**'], True]
  - empty: True
  - name: fooId
  - type: hidden
  - value: **[id is here]**
- type: hidden
- value: **[id is here]**

**[id is here]**
**[id is here too]**
**[id is HERE too]**
**[and id is even here TOO]**

Вы можете видеть, что не только pyparsing соответствует этим непредсказуемым вариациям, он возвращает данные в объекте, что упрощает считывание отдельных атрибутов тегов и их значений.

1
ответ дан 3 December 2019 в 00:48
поделиться
Другие вопросы по тегам:

Похожие вопросы: