"""
保存一个商店中的书的信息:
json:
{
name: '新华书店',
books: [
{
name: '流程的Python'
author: '张三'
price: 120
num: 20
},
{
name: '代码整洁之道'
author: '小明'
price: 89
num: 12
},
{
name: '程序员修养之道- 从小工到专家'
author: 'Bob'
price: 78
num:23
},
{
name: 'Unix编程艺术'
author: '小花'
price: 102
num: 9
}
]
}
<bookStore>
<name>新华书店</name>
<books>
<book>
<name flag="hot">流程的Python</name>
<author>张三</author>
<price>120</price>
<num>20</num>
</book>
<book>
<name>代码整洁之道</name>
<author>小明</author>
<price>89</price>
<num>12</num>
</book>
<book>
<name>程序员修养之道- 从小工到专家</name>
<author>Bob</author>
<price>78</price>
<num>23</num>
</book>
<book>
<name>Unix编程艺术</name>
<author>小花</author>
<price>102</price>
<num>9</num>
</book>
</books>
</bookStore>
"""
from lxml import etree
with open('data.xml', encoding='utf-8') as f:
data = f.read()
bookStore = etree.XML(data)
print(bookStore)
result = bookStore.xpath('/bookStore/books/book/author')
print(result)
result = bookStore.xpath('/bookStore/name')
print(result)
book_list = bookStore.xpath('/bookStore/books/book')
print(book_list)
book_list = result[0].xpath('/bookStore/books/book')
print(book_list)
name_list = bookStore.xpath('//name')
print(name_list)
name_list = bookStore.xpath('//book/name')
print(name_list)
name_list = bookStore.xpath('./name')
print(name_list)
name_list = bookStore.xpath('./books/book/name')
print(name_list)
result = book_list[0].xpath('./name/text()')
print(result)
result = book_list[0].xpath('name/text()')
print(result)
name_list = bookStore.xpath('//name')
name_1 = name_list[0]
result = name_1.xpath('..')
print(result)
result = name_1.xpath('../books')
print(result)
store_name = bookStore.xpath('/bookStore/name/text()')
print(store_name)
store_name = bookStore.xpath('//name')[0].xpath('./text()')
print(store_name)
result = bookStore.xpath('//text()')
print(result)
flag = bookStore.xpath('//book/name')[0].xpath('./@flag')
print(flag)
ids = bookStore.xpath('//book/@id')
print(ids)
name_1 = bookStore.xpath('//book[1]/name/text()')
print(name_1)
name_last = bookStore.xpath('//book[last()]/name/text()')
print(name_last)
name_last_2 = bookStore.xpath('//book[last()-1]/name/text()')
print(name_last_2)
book_list = bookStore.xpath('//books/book[position()<4]/author/text()')
print(book_list)
book_list = bookStore.xpath('//books/book[position()>2]/author/text()')
print(book_list)
flags = bookStore.xpath('//name[@flag]/text()')
print(flags)
flags = bookStore.xpath('//name[@flag="hot"]/text()')
print(flags)
book_list = bookStore.xpath('//books/book[@id>200]')
print(book_list)
book_list = bookStore.xpath('//book[name="流程的Python"]')
print(book_list)
book_list = bookStore.xpath('//book[price>100]/name/text()')
print(book_list)
result = bookStore.xpath('//book[1]/*/text()')
print(result)
result = bookStore.xpath('//*[@id]')
print(result)
result = bookStore.xpath('//*[@*]')
print(result)
result = bookStore.xpath('//book[@id=100]')
print(result)
result = bookStore.xpath('//book[1]/name/text()|//book[1]/price/text()')
print(result)
from lxml import etree
import requests
def get_data():
url = 'https://movie.douban.com/top250'
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36'
}
response = requests.get(url, headers=headers)
if response.status_code == 200:
xpath_analysis(response.text)
else:
print('请求失败!', response)
def xpath_analysis(data):
html = etree.HTML(data)
li_list = html.xpath('//ol[@class="grid_view"]/li')
all_f_info = []
for li in li_list:
f_info = {}
names = li.xpath('./div/div[@class="info"]/div[@class="hd"]/a/span/text()')
f_info['name'] = names[0]
director = li.xpath('./div/div[@class="info"]/div[@class="bd"]/p[1]/text()')
director = [x.strip() for x in director]
f_info['director'] = director[0]
f_info['time_type'] = director[1]
score = li.xpath('./div/div[@class="info"]/div[@class="bd"]/div/span[@class="rating_num"]/text()')
f_info['score'] = score[0]
all_f_info.append(f_info)
print(all_f_info)
if __name__ == '__main__':
get_data()
import csv
def write_data1():
with open('files/data1.csv', 'w', newline='')as f:
writer = csv.writer(f)
writer.writerow(['姓名', '性别', '年龄', '电话'])
writer.writerows([
['张三', '男', '30', '123'],
['李四', '女', '22', '321']
])
def write_data2():
with open('files/data2.csv', 'w', encoding='utf-8', newline='') as f:
writer = csv.DictWriter(f, ['name', 'sex', 'age', 'tel'])
writer.writeheader()
writer.writerow({
'name': '张三',
'sex': '男',
'age': 30,
'tel': '110'
})
writer.writerows([
{'name': '小明', 'sex': '男', 'age': 19, 'tel': '119'},
{'name': '小红', 'sex': '女', 'age': 21, 'tel': '114'}
])
write_data2()
def reader_list():
with open('files/data1.csv', encoding='gbk', newline='') as f:
reader = csv.reader(f)
print(reader)
print(next(reader))
print(next(reader))
print('============')
for x in reader:
print(x)
def reader_dict():
with open('files/data1.csv', encoding='gbk', newline='') as f:
reader = csv.DictReader(f, ['name', 'sex', 'age', 'tel'])
next(reader)
print(dict(next(reader)))
for x in reader:
print(dict(x))
reader_dict()