爬虫代码已复制

S03 - lxml库进阶语法及解析练习

1718093665阅读数:203
上一篇:S02 - http请求分析及头构造使用
下一篇:S04 - 分页参数分析及翻页爬取
# coding=utf-8

import requests
from lxml import etree

url = 'http://www.spiderbuf.cn/playground/s03'

myheaders = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.164 Safari/537.36'}

html = requests.get(url, headers=myheaders).text
print(html)

f = open('03.html', 'w', encoding='utf-8')
f.write(html)
f.close()

root = etree.HTML(html)
trs = root.xpath('//tr')

f = open('data03.txt', 'w', encoding='utf-8')
for tr in trs:
    tds = tr.xpath('./td')
    s = ''
    for td in tds:
        s = s + str(td.xpath('string(.)')) + '|'
        # s = s + str(td.text) + '|'
    print(s)
    if s != '':
        f.write(s + '\n')

f.close()