0

I wanted to print a specific line from my HTML file. The specific line being the one enclosed as a header. My test.html file is posted at the bottom for reference

import codecs
import re
f = codecs.open("test.html", 'r')
f.read()
paragraphs = re.findall(r'<html>(.*?)</html>',str(f))
print(paragraphs)
f.close()

test.html looks like this

<html>
<head>
<title>
Example
</title>
</head>
<body>
<h1>Hello, world</h1>
</body>
</html>
0

1 Answer 1

3

you could do something like this:

import codecs
import re
g = codecs.open("test.html", 'r')
f = g.read()
start = f.find("<head>")
start = start + 7
end =  f.find("</head>")
end = end - 1
paragraphs = f[start:end]
print(paragraphs)
g.close()

this prints

<title>
Example
</title>

.find() returns the starting index of the substring inside the string you searched, then we use those indexes (after applying some simple math) to access the substring by slicing the string with [:].

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.