【问题标题】:How to print a specific line in string Python?如何在字符串 Python 中打印特定行?
【发布时间】:2021-09-15 10:55:35
【问题描述】:

所以我在网络爬取时从css选择器中得到了一个字符串输出,该字符串有7行,其中6行没用,我只想要第4行。

字符串如下:

کارکرد:
۵۰,۰۰۰
رنگ:
سفید
وضعیت بدنه:
بدون رنگ
قیمت صفر : ۳۱۵,۰۰۰,۰۰۰ تومان

有没有办法只打印第 4 行?

爬取代码:

color = driver.find_elements_by_css_selector("div[class='col']") 
for c in color:
    print(c.text)

【问题讨论】:

  • 哪个变量包含字符串?

标签: python string web-crawler


【解决方案1】:

是的,当然! See python documentation about list items

color = driver.find_elements_by_css_selector("div[class='col']") 
print(color[3].text)

列表项被索引,第一项的索引为[0],第二项的索引为1等等。

【讨论】:

  • 我正在尝试“枚举”,但我很困惑。真的很有帮助,谢谢!
【解决方案2】:

我不确定我是否正确理解了这个问题,但假设您有一个包含多行的字符串,解决方案可能是:

string = '''this string
exists 
on multiple
lines
so lets pick
a line
'''

def select_line(string, line_index):
    return string.splitlines()[line_index]

result = select_line(string,3)

print(result)

这个函数会选择你想要的数字行(索引 0 是第一行)

【讨论】:

    【解决方案3】:

    如果你想要 onefour 的项目,试试这个:

    for idx in range(4):
        print(color[idx].text)
    

    如果你只想要4th 试试这个:(在list 的python 索引中从zero 开始。)

    print(color[3].text)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多