Pyparsing là bước tạm thời tốt giữa BeautifulSoup và regex. Nó mạnh mẽ hơn chỉ là regex, vì việc phân tích cú pháp thẻ HTML của nó hiểu các biến thể trong trường hợp, khoảng trắng, sự hiện diện/thiếu/thuộc tính của thuộc tính, nhưng đơn giản hơn để thực hiện loại trích xuất thẻ cơ bản này hơn là sử dụng BS.
Ví dụ của bạn đặc biệt đơn giản vì mọi thứ bạn đang tìm đều nằm trong thuộc tính của thẻ "đầu vào" mở. Dưới đây là một ví dụ pyparsing cho thấy nhiều biến thể trên thẻ đầu vào của bạn mà sẽ cung cấp cho phù hợp regexes, và cũng cho thấy cách KHÔNG để phù hợp với một thẻ nếu nó nằm trong một bình luận:
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]**
Bạn có thể thấy rằng không chỉ pyparsing phù hợp với các biến thể không thể đoán trước, nó trả về dữ liệu trong một đối tượng mà làm cho nó dễ dàng để đọc ra các thuộc tính thẻ cá nhân và giá trị của chúng.
Tôi nghĩ rằng từ khóa "mới" là không phù hợp. –