python - XPath 删除列表 Python 中的空格

标签 python xpath export-to-csv

我已经尝试了我所知道的一切,但似乎找不到解决方案。

import csv
import requests
from lxml import html
from itertools import izip

list_names_atp = []
page = requests.get('http://www.atpworldtour.com/en/rankings/singles')
tree = html.fromstring(page.content)

list_rank_atp = []
for i in range(0,101):
    result = tree.xpath('//*[@id="rankingDetailAjaxContainer"]/table/tbody/tr[%s]/td[1]/text()'%(i))
    list_rank_atp.append(result)

list_names_atp = []
for i in range(0,101):
    result1 = tree.xpath('//*[@id="rankingDetailAjaxContainer"]/table/tbody/tr[%s]/td[4]/a/text()'%(i))
    list_names_atp.append(result1)

list_Final =[]
for i in izip(list_rank_atp, list_names_atp):
    uitkom = i
    list_Final.append(uitkom)

outfile = open("./tennis.csv", "wb")
writer = csv.writer(outfile)
writer.writerow(["Rank", "Name"])
writer.writerows(list_Final)    

csv 输出如下:

enter image description here

但我希望它是:

enter image description here

最佳答案

以下是一些注释:

  • XPath 索引从 1 开始,而不是从 0 开始。这就是为什么第一个数据行的条目为空。

  • 您可以使用 Python 的 strip() 或 XPath 的 normalize-space() 删除行号文本周围的空格

我建议迭代行(tr)并在每次迭代中从当前行获取所需的所有信息:

page = requests.get('http://www.atpworldtour.com/en/rankings/singles')
tree = html.fromstring(page.content)
outfile = open("./tennis.csv", "wb")
writer = csv.writer(outfile)

rows = tree.xpath('//*[@id="rankingDetailAjaxContainer"]/table/tbody/tr')
writer.writerow(["Rank", "Name"])

for row in rows:
    no = row.xpath('td[1]/text()')[0].strip()
    name = row.xpath('td[4]/a/text()')[0]
    writer.writerow([no, name])

outfile.close()

关于python - XPath 删除列表 Python 中的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36810583/

相关文章:

python - 如何为每个时期保存keras模型的权重?

Python 字典/循环输出

python - 迭代列表的不同方法

css - 如何获取包裹在 <p> 标签下的段落中的文本的 CSS 选择器

python - 为什么我没有从网站取回任何数据?

xml - 在 xsl 中拆分字符串并更新属性

android - 将 sqlite 导出到 csv

python - 在 Matlab 中对于矩阵(m,n)等效矩阵(:) , 冒号,在 python 中

php - 如何使用 php 将 mysql 数据表搜索查询导出到 csv?

data-binding - 在 openUI5 的 csv 导出中删除不需要的换行符