简体   繁体   English

如何在 python 3.x 中打印格式化数组?

[英]How can I print a formatted array in python 3.x?

I trying to write a web-scraper for wordreference.com, the code is this:我试图为 wordreference.com 编写一个网络爬虫,代码是这样的:

import bs4,sys, requests
from urllib import request

def scraper():
    url=f"https://wordreference.com/iten/{sys.argv[1]}"
    r=requests.get(url)
    html=r.text
    soup=bs4.BeautifulSoup(html, "html.parser")
    x=soup.find_all("td","ToWrd")
    print(x[1].contents)

if __name__ == "__main__":
    scraper()

The code is right but the output is this: input:代码是正确的,但 output 是这样的:输入:

python3 scraper.py cane

Output: Output:

['dog ', <em class="tooltip POS2">n<span><i>noun</i>: Refers to person, place, thing, quality, etc.</span></em>]]

I want print only the first part of array, when is contained 'dog'.我只想打印数组的第一部分,什么时候包含“狗”。 How can I resolve this problem?我该如何解决这个问题?

well here is the code:那么这里是代码:

print(x[1].contents[0])

x[1].contents returns a list, so to access the string 'dog ', you need to specify index 0 x[1].contents 返回一个列表,因此要访问字符串 'dog',您需要指定索引 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 Python 3.x 中逐行打印网页 - How can I print a webpage line by line in Python 3.x Python 3.x:打印特定的数组项 - Python 3.x: Print specific array items 如何在Python 3.x中从格式化的文本文件中识别和存储变量和数据? - How can one identify and store variables and data from a formatted text file in Python 3.x? 我可以将 Python 3.6 的格式化字符串文字 (f-strings) 导入到旧的 3.x、2.x Python 中吗? - Can I import Python's 3.6's formatted string literals (f-strings) into older 3.x, 2.x Python? 如何在Python 3.x中验证日期? - How can I validate a date in Python 3.x? 如何在 Python 3.x 中检查字符串中的新行? - How can I check for a new line in string in Python 3.x? 如何在python中打印列表? (应格式化) - How can I print list in python? (should be formatted) 如何在 python 中使用这种样式格式的文本打印花括号 - How can I print curly braces with this style formatted text in python 如何在每次 [Python 3.x] 的不同输出的同一行(shell 或窗口)中重新打印 2D 数组或多个输出? - How can I reprint 2D array or multiple outputs in the same line of (shell or window) with different output each time [Python 3.x]? 在Python 3.x中,如何替换列表中的某些项目,然后将列表打印为字符串 - In Python 3.x, how do I replace certain items in a list then print list as a string
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM