使用Beautiful Soup搜寻HTML

时间:2018-08-21 03:23:13

标签: python html beautifulsoup

#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)

1 个答案:

答案 0 :(得分:0)

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

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

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