CSS选择器 + Xpath + 正则表达式整理(有空再整理)

选择器例子例子描述CSS
.class .intro 选择 class="intro" 的所有元素。 1
#id #firstname 选择 id="firstname" 的所有元素。 1
* * 选择所有元素。 2
element p 选择所有 <p> 元素。 1
element,element div,p 选择所有 <div> 元素和所有 <p> 元素。 1
element element div p 选择 <div> 元素内部的所有 <p> 元素。 1
element>element div>p 选择父元素为 <div> 元素的所有 <p> 元素。 2
element+element div+p 选择紧接在 <div> 元素之后的所有 <p> 元素。 2
[attribute] [target] 选择带有 target 属性所有元素。 2
[attribute=value] [target=_blank] 选择 target="_blank" 的所有元素。 2
[attribute~=value] [title~=flower] 选择 title 属性包含单词 "flower" 的所有元素。 2
[attribute|=value] [lang|=en] 选择 lang 属性值以 "en" 开头的所有元素。 2
:link a:link 选择所有未被访问的链接。 1
:visited a:visited 选择所有已被访问的链接。 1
:active a:active 选择活动链接。 1
:hover a:hover 选择鼠标指针位于其上的链接。 1
:focus input:focus 选择获得焦点的 input 元素。 2
:first-letter p:first-letter 选择每个 <p> 元素的首字母。 1
:first-line p:first-line 选择每个 <p> 元素的首行。 1
:first-child p:first-child 选择属于父元素的第一个子元素的每个 <p> 元素。 2
:before p:before 在每个 <p> 元素的内容之前插入内容。 2
:after p:after 在每个 <p> 元素的内容之后插入内容。 2
:lang(language) p:lang(it) 选择带有以 "it" 开头的 lang 属性值的每个 <p> 元素。 2
element1~element2 p~ul 选择前面有 <p> 元素的每个 <ul> 元素。 3
[attribute^=value] a[src^="https"] 选择其 src 属性值以 "https" 开头的每个 <a> 元素。 3
[attribute$=value] a[src$=".pdf"] 选择其 src 属性以 ".pdf" 结尾的所有 <a> 元素。 3
[attribute*=value] a[src*="abc"] 选择其 src 属性中包含 "abc" 子串的每个 <a> 元素。 3
:first-of-type p:first-of-type 选择属于其父元素的首个 <p> 元素的每个 <p> 元素。 3
:last-of-type p:last-of-type 选择属于其父元素的最后 <p> 元素的每个 <p> 元素。 3
:only-of-type p:only-of-type 选择属于其父元素唯一的 <p> 元素的每个 <p> 元素。 3
:only-child p:only-child 选择属于其父元素的唯一子元素的每个 <p> 元素。 3
:nth-child(n) p:nth-child(2) 选择属于其父元素的第二个子元素的每个 <p> 元素。 3
:nth-last-child(n) p:nth-last-child(2) 同上,从最后一个子元素开始计数。 3
:nth-of-type(n) p:nth-of-type(2) 选择属于其父元素第二个 <p> 元素的每个 <p> 元素。 3
:nth-last-of-type(n) p:nth-last-of-type(2) 同上,但是从最后一个子元素开始计数。 3
:last-child p:last-child 选择属于其父元素最后一个子元素每个 <p> 元素。 3
:root :root 选择文档的根元素。 3
:empty p:empty 选择没有子元素的每个 <p> 元素(包括文本节点)。 3
:target #news:target 选择当前活动的 #news 元素。 3
:enabled input:enabled 选择每个启用的 <input> 元素。 3
:disabled input:disabled 选择每个禁用的 <input> 元素 3
:checked input:checked 选择每个被选中的 <input> 元素。 3
:not(selector) :not(p) 选择非 <p> 元素的每个元素。 3
::selection ::selection 选择被用户选取的元素部分。 3

 http://www.w3school.com.cn/cssref/css_selectors.asp

 CSS选择器

response.css('a[_stat="videolist:title"]::attr(href)').extract_first()
response.css('#endText p img::attr(src)')
response.css('h1::text')


response.css('div[class="video_tags"] ::text').extract()
response.css('a[_stat="videolist:title"]::attr(href)').extract_first()
episodes_nodes = response.css('div[class="mod_figure"][_wind="columnname=本期看点"] ul li')   # 多个属性
details = response.css(".synopsis p span::text").extract_first()

download_urls = response.css("div[class='list download'] div[class='body active'] ul[class^='bill']>li").extract() # ^= 可以选择属性以bill开头的ul元素,ul>li选择ul下面第一层li,而不是ul下面所有li

node_url = node.css("a[href^='/download/']::attr(href)").extract_first("")

记录一个问题:

 当连续使用css选择器时,出现这种错误:AttributeError: 'str' object has no attribute 'css'

例如这个程序:

property_info = response.css(".property .body ul li").extract()

property_dict = {}
for node in property_info:
    head = node.css("dl dt::text").extract_first()
    value = node.css("dl dd a::text").extract()
    if not value:
        value = node.css("dl dd::text").extract()

    property_dict[head] = value    

错误就在第一句不应该加extract()

Xpath

xpath语法:

http://www.runoob.com/xpath/xpath-syntax.html

选取节点

XPath 使用路径表达式在 XML 文档中选取节点。节点是通过沿着路径或者 step 来选取的。 下面列出了最有用的路径表达式:

表达式描述
nodename 选取此节点的所有子节点。
/ 从根节点选取。
// 从匹配选择的当前节点选择文档中的节点,而不考虑它们的位置。
. 选取当前节点。
.. 选取当前节点的父节点。
@ 选取属性。


 

在下面的表格中,我们已列出了一些路径表达式以及表达式的结果: 

路径表达式结果
bookstore 选取 bookstore 元素的所有子节点。
/bookstore

选取根元素 bookstore。

注释:假如路径起始于正斜杠( / ),则此路径始终代表到某元素的绝对路径!

bookstore/book 选取属于 bookstore 的子元素的所有 book 元素。
//book 选取所有 book 子元素,而不管它们在文档中的位置。
bookstore//book 选择属于 bookstore 元素的后代的所有 book 元素,而不管它们位于 bookstore 之下的什么位置。
//@lang 选取名为 lang 的所有属性。

谓语(Predicates)

谓语用来查找某个特定的节点或者包含某个指定的值的节点。

谓语被嵌在方括号中。

在下面的表格中,我们列出了带有谓语的一些路径表达式,以及表达式的结果:

路径表达式结果
/bookstore/book[1] 选取属于 bookstore 子元素的第一个 book 元素。
/bookstore/book[last()] 选取属于 bookstore 子元素的最后一个 book 元素。
/bookstore/book[last()-1] 选取属于 bookstore 子元素的倒数第二个 book 元素。
/bookstore/book[position()<3] 选取最前面的两个属于 bookstore 元素的子元素的 book 元素。
//title[@lang] 选取所有拥有名为 lang 的属性的 title 元素。
//title[@lang='eng'] 选取所有 title 元素,且这些元素拥有值为 eng 的 lang 属性。
/bookstore/book[price>35.00] 选取 bookstore 元素的所有 book 元素,且其中的 price 元素的值须大于 35.00。
/bookstore/book[price>35.00]/title 选取 bookstore 元素中的 book 元素的所有 title 元素,且其中的 price 元素的值须大于 35.00。

 

 

 

选取未知节点

XPath 通配符可用来选取未知的 XML 元素。

通配符描述
* 匹配任何元素节点。
@* 匹配任何属性节点。
node() 匹配任何类型的节点。

在下面的表格中,我们列出了一些路径表达式,以及这些表达式的结果:

路径表达式结果
/bookstore/* 选取 bookstore 元素的所有子元素。
//* 选取文档中的所有元素。
//title[@*] 选取所有带有属性的 title 元素。

选取若干路径

通过在路径表达式中使用"|"运算符,您可以选取若干个路径。

在下面的表格中,我们列出了一些路径表达式,以及这些表达式的结果:

路径表达式结果
//book/title | //book/price 选取 book 元素的所有 title 和 price 元素。
//title | //price 选取文档中的所有 title 和 price 元素。
/bookstore/book/title | //price 选取属于 bookstore 元素的 book 元素的所有 title 元素,以及文档中所有的 price 元素。
tree.xpath('//div[@id="endText"]/p//text() | //div[@id="endText"]/p/a/text()')

#对selector进一步使用Xpath时,Xpath表达式最前面不要加/
nodes_tr = tree.xpath('//div[@id="endText"]//table/tbody/tr') 
for node in nodes_tr:
    link_text = node.xpath('td/text() | td/a/text()')

response.xpath('//a[@_stat="videolist:title"]/@href')
import requests
import lxml.html as html


def html_handle(response):
    # r = requests.get(url)
    # r.encoding = 'gb2312'

    tree = html.fromstring(response.text)
    nodes = tree.xpath('//div[@id="endText"]/p//text() | //div[@id="endText"]/p/a/text()')
    print(nodes)
    content = "".join(nodes)
    # print(content)
    return nodes,content

正则表达式:

参考链接:Python正则表达式 - 菜鸟教程

Python re 模块:

1、search(pattern, string, flags=0)      在一个字符串中查找匹配

2、findall(pattern, string ,flags=0)     找到匹配,返回所有匹配部分的列表

3、sub(pattern, repl, string , count=0, flags=0)    将字符串中匹配正则表达式的部分替换为其他值

4、split(pattern, string ,maxsplit=0, flags=0)  根据匹配分割字符串,返回分隔符串组成的列表

正则表达式可以包含一些可选标志修饰符来控制匹配的模式。修饰符被指定为一个可选的标志。多个标志可以通过按位 OR(|) 它们来指定。如 re.I | re.M 被设置成 I 和 M 标志:

修饰符 描述
re.I   使匹配对大小写不敏感
re.L   做本地化识别(locale-aware)匹配
re.M   多行匹配,影响 ^ 和 $
re.S   使 . 匹配包括换行在内的所有字符
re.U   根据Unicode字符集解析字符。这个标志影响 w, W, , B.
re.X   该标志通过给予你更灵活的格式以便你将正则表达式写得更易于理解。


正则表达式默认只匹配一行, 加re.DOTALL可以匹配全文,匹配多行 

match_obj = re.match('.*name="_xsrf" value="(.*?)"', response_text, re.DOTALL)

Python中字符串前面加上 r 表示原生字符串  

https://blog.csdn.net/xlengji/article/details/80991004

与大多数编程语言相同,正则表达式里使用""作为转义字符,这就可能造成反斜杠困扰。假如你需要匹配文本中的字符"",那么使用编程语言表示的正则表达式里将需要4个反斜杠"\":前两个和后两个分别用于在编程语言里转义成反斜杠,转换成两个反斜杠后再在正则表达式里转义成一个反斜杠。    Python里的原生字符串很好地解决了这个问题,有了原生字符串,你再也不用担心是不是漏写了反斜杠,写出来的表达式也更直观。

 

例子:

match = re.match(r".*第(.*)季.*", str)
# 等价于
match = re.search(r"第(.*)季", str)
# 生活大爆炸第十二季 - 第16集.mp4
match = re.match(r".*第(.*?)集.*", episode_name)
def get_season(str):
    match = re.search(r"第(.*)季", str)
    if match:
        season = match.group(1)
        print(season + "*********")
    else:
        season = ""
    return season
原文地址:https://www.cnblogs.com/tanrong/p/9937222.html