XPath for html elements - python

I'd like to use Scrapy to crawl a few hundred websites and just scrape the basic (title, meta* and body) html elements. I know that I should use CrawlSpider for this and adjust some of the settings based on broad crawls. The part that I'm having trouble figuring it out is how to use xpath to create the rules for scraping just those basic html elements. Lots of tutorials I see involve inspecting the element and finding the css class for that element. That is fine for the body element but what about the title and meta tags?

There XPath and CSS selector you can use to select nodes in HTML.
the element is a node, but the node not always an element.
So, then you know head, meta, body are all elements. the class attributes in the div is the same as the charset attribute in meta element. They are all attributes nodes.
e.g:
<!DOCTYPE html>
<html lang='zh-cn'>
<head>
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="renderer" content="webkit">
<title>title</title>
</head>
<body>
<div>website content</div>
</body>
</html>
if you want to select
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
you can use XPATH like this:
//head/meta[#http-equiv="X-UA-Compatible"]

You can search the elements in <head> the same way you find in <body>, for example:
//html/head/title
or
//html/head/meta

Well for the title node you can write a simple XPath expression : //title which is the abbreviated syntax of /descendant-or-self::node()/child::title and that's it.
For the meta node guess what you can just write //meta too or if you want you can use the absolute path /html/head/meta
PS. You can do the same thing for the body node.

Related

SCRAPY - XPATH select a object inside a node

I need to get an object inside a variable inside a node which is a javascript node.
(Using scrapy 1.8.0 didn't update yet hehe)
Maybe I don't explain myself clearly but as soon you see it... you will understand.
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script id='myscript'>
oneVariable = {...}
theVariable = {"Data": "blahblah", "More-Data": {...}}
</script>
</head>
<body>
</body>
</html>
Ok I got the whole node with his information manually using scrapy shell and then the selector
response.xpath('//*[#id="myscript"]').get()
Can I get the "theVariable" I want just with XPATH selectors or functions (like get(), getAll() etc)?
Thanks in advance!
Try changing you xpath expression to something like:
substring-after(//script[#id="myscript"],"theVariable = ")

lxml: Element is not a child of this node

I'm trying to change the value of title within the following html document:
<html lang="en">
<head>
<meta charset="utf-8">
<title id="title"></title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<app-root></app-root>
</body>
</html>
I wrote the following python script which uses lxml, in order to accomplish the task:
from lxml.html import fromstring, tostring
from lxml.html import builder as E
html = fromstring(open('./index.html').read())
html.replace(html.get_element_by_id('title'), E.TITLE('TEST'))
But after running the script, I get the following error:
ValueError: Element is not a child of this node.
What's supposed to cause this error? Thank you.
The 'title' tag is a child of the 'head' node. In your code you use replace on the 'html' node, which has no 'title' elements (not directly), hence the ValueError.
You can get the desired results if you use replace on the 'head' node.
html.find('head').replace(html.get_element_by_id('title'), E.TITLE('TEST'))

How do I pass the elements of a Python list to HTML for different HREF links?

I have a list of filenames in Python, and I want to pass that to HTML. The HTML page should have different href links for each of the filenames in the list. If I pass the whole list then the href link is again a list (which does not allow me to click on different links), and if I use a for loop to pass the list elements one by one, it is getting displayed as different HTML pages.
EDIT: Here is my code. 'docs' is a list of filenames. This is printing "Results" followed by first link, then "Results" followed by second link, and so on. I want it to display "Results" and then all the links one below the other. Basically, I want the loop only for the 'a href' part.
def results(docs):
template = """
<html>
<head>
<title> Results </title>
</head>
<body>
%s
</body>
</html>
"""
html = ""
for i in range(len(docs)):
html = '\n'.join([html, template % (docs[i], docs[i])])
return html
PS: Sorry if the question is unclear, it is the first time I am posting a question on stackoverflow.
I'd actually use a template engine, like Mako. Working example:
from mako.template import Template
def results(docs):
template = """
<html>
<head>
<title> Results </title>
</head>
<body>
% for doc in docs:
${doc}
% endfor
</body>
</html>
"""
return Template(template).render(docs=docs)
print(results(["link1", "link2"]))
Prints:
<html>
<head>
<title> Results </title>
</head>
<body>
link1
link2
</body>
</html>

Getting BeautifulSoup to catch tags in a non-case-sensitive way

I want to catch some tags with BeautifulSoup: Some <p> tags, the <title> tag, some <meta> tags. But I want to catch them regardless of their case; I know that some sites do meta like this: <META> and I want to be able to catch that.
I noticed that BeautifulSoup is case-sensitive by default. How do I catch these tags in a non-case-sensitive way?
BeautifulSoup standardises the parse tree on input. It converts tags to lower-case. You don't have anything to worry about IMO.
You can use soup.findAll which should match case-insensitively:
import BeautifulSoup
html = '''<html>
<head>
<meta name="description" content="Free Web tutorials on HTML, CSS, XML" />
<META name="keywords" content="HTML, CSS, XML" />
<title>Test</title>
</head>
<body>
</body>
</html>'''
soup = BeautifulSoup.BeautifulSoup(html)
for x in soup.findAll('meta'):
print x
Result:
<meta name="description" content="Free Web tutorials on HTML, CSS, XML" />
<meta name="keywords" content="HTML, CSS, XML" />

Get document DOCTYPE with BeautifulSoup

I've just started tinkering with scrapy in conjunction with BeautifulSoup and I'm wondering if I'm missing something very obvious but I can't seem to figure out how to get the doctype of a returned html document from the resulting soup object.
Given the following html:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<meta charset=utf-8 />
<meta name="viewport" content="width=620" />
<title>HTML5 Demos and Examples</title>
<link rel="stylesheet" href="/css/html5demos.css" type="text/css" />
<script src="js/h5utils.js"></script>
</head>
<body>
<p id="firstpara" align="center">This is paragraph <b>one</b>
<p id="secondpara" align="blah">This is paragraph <b>two</b>.
</html>
Can anyone tell me if there's a way of extracting the declared doctype from it using BeautifulSoup?
Beautiful Soup 4 has a class for DOCTYPE declarations, so you can use that to extract all the declarations at top level (though you're no doubt expecting one or none!)
def doctype(soup):
items = [item for item in soup.contents if isinstance(item, bs4.Doctype)]
return items[0] if items else None
You can go through top-level elements and check each to see whether it is a declaration. Then you can inspect it to find out what kind of declaration it is:
for child in soup.contents:
if isinstance(child, BS.Declaration):
declaration_type = child.string.split()[0]
if declaration_type.upper() == 'DOCTYPE':
declaration = child
You could just fetch the first item in soup contents:
>>> soup.contents[0]
u'DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"'

Categories