【问题标题】:Crawling html using Beautiful Soup使用 Beautiful Soup 抓取 html
【发布时间】:2018-08-21 03:23:12
【问题描述】:
#searchMenu > div.menu_wrap > ul > li.first.actived > div > div > div > 
div.menu_con.ng-scope > ul > li.actived > div > div.result_list > div > ul 
> li:nth-child(1) > ul > li:nth-child(3)

所以我想像这样提取所有元素。

li:nth-child(1) > ul > li:nth-child(3)
li:nth-child(2) > ul > li:nth-child(3)
li:nth-child(3) > ul > li:nth-child(3)
li:nth-child(4) > ul > li:nth-child(3)
li:nth-child(5) > ul > li:nth-child(3)

如何使用'for循环'编写代码?

我刚试过这段代码:

address = [] 

for book in tags: 
    tag = book.select_one('li:nth-of-type(4) ').text address.append(tag)
    print(address)

【问题讨论】:

  • 你试过什么?发生了什么?
  • 我刚试过这段代码。 address = [] for book in tags: tag = book.select_one('li:nth-of-type(4) ').text address.append(tag) print(address)
  • 能否提供整个div的实际HTML代码?
  • 您可以使用edit 按钮来改进您的问题并添加更多信息。

标签: python html beautifulsoup


【解决方案1】:

枚举标签并将索引值传递给您的选择器。像这样,

for i, book in enumerate(tags): 
    tag = book.select_one('li:nth-of-type('+str(i)+') ').text address.append(tag)
    print(address)

希望这会有所帮助!干杯!

【讨论】:

  • 如果我的回答为您的问题提供了解决方案,请点赞并接受。这是 SO 中的道德规范。
猜你喜欢
  • 1970-01-01
  • 2023-03-31
  • 2017-03-30
  • 2023-03-20
  • 1970-01-01
  • 2022-08-22
  • 2013-01-09
  • 2022-01-07
  • 2016-05-16
相关资源
最近更新 更多