Example of using the Xpath expression in urllib, urllibxpath

Source: Internet
Author: User

Example of using the Xpath expression in urllib, urllibxpath
Example of using Xpath expressions in urllib

To use an xpath expression, you must first convert the data to be matched to the tree format. Therefore, you must first install the lxml module. You can use pip to install the SDK.

Sample Code:

Import urllib. requestfrom lxml import etree date = urllib. request. urlopen ("http://www.sohu.com /"). read (). decode ("UTF-8", "ignore") treedate = etree. HTML (date) # convert the data obtained by urllib to the etree structure title = treedate. xpath ("// title/text ()") # use an xpath expression to obtain the expected data if (str (type (title ))) = "<class 'LIST'>": # This avoids the format of some data, such as the iterator. Therefore, you can determine the acquired data type and convert it to the list type passelse: title = [I for I in title] # convert data to list type through Traversal

Additional knowledge points:

>>> [I for I in range (1, 10)] [1, 2, 3, 4, 5, 6, 7, 8, 9]

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.