靓汤不速之客

2024-04-19 21:05:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习美丽的汤,我遵循分析维迪亚的一个简短教程,可以在这里找到:https://www.analyticsvidhya.com/blog/2015/10/beginner-guide-web-scraping-beautiful-soup-python/

本教程使用Beautiful Soup在维基百科中删除一个网页:“https://en.wikipedia.org/wiki/List_of_state_and_union_territory_capitals_in_India

我在Jupyter笔记本中运行这些命令,除了从表标记中提取信息外,其他输出都是相同的。你知道吗

本教程使用以下命令提取特定表的内容:

  soup.find_all("table" , class_ = 'wikitable sortable plainrowheaders' ) 

根据教程,其结果如下:

enter image description here

但是,当我运行同一个命令时,会得到一个混乱的输出,不太可读,如下所示:

   [<table class="wikitable sortable plainrowheaders">\n<tr>\n<th 
   scope="col">No.</th>\n<th scope="col">State or<br/>\nunion  
    territory</th>\n<th scope="col">Administrative capitals</th>\n<th   
    scope="col">Legislative capitals</th>\n<th scope="col">Judiciary 

你能解释一下输出的差别吗?你知道吗

谢谢你的建议。你知道吗


Tags: https命令wwwtable教程colclassscope
2条回答

它可能是相同的输出,只是您的特定开发环境对它的处理方式不同。你总是可以导入“漂亮的打印”,看看这是否能让事情变好:

from pprint import pprint

pprint(my_output)

最后我找到了答案。你知道吗

使用prettify()方法可以使打印输出更可读。但是,find_all()方法返回一个ResultSet,其中包含 键入“Table”和给定的属性。无法将prettify()方法应用于结果集。但是,prettify()可以应用于切片返回的结果集的元素。因此,要获得表的可打印输出,我们执行以下操作:

  right_tables = soup.find_all("table" , class_ = 'wikitable sortable plainrowheaders' ) 
  print(right_tables[0].prettify())

这将呈现以下输出,这正是我要查找的:

  <table class="wikitable sortable plainrowheaders">
   <tr>
    <th scope="col">
      No.
    </th>
    <th scope="col">
      State or
      <br/>
         union territory
    </th>

等等

相关问题 更多 >