合并下列代码info = soup.select(f'#main > div:nth-child({i}) > ul') info1 = soup.select('#main > div:nth-child({i}) > h2')
时间: 2024-03-20 19:38:52 浏览: 93
将它们合并成一个代码行,并且使用 f-string 进行字符串格式化,如下所示:
```
info = soup.select(f"#main > div:nth-child({i}) > ul")
info1 = soup.select(f"#main > div:nth-child({i}) > h2")
```
这样可以使代码更加简洁和易读。
相关问题
合并成一行代码info = soup.select(f"#main > div:nth-child({i}) > ul")info1 = soup.select(f"#main > div:nth-child({i}) > h2")
虽然将两行代码合并成一行可以减少代码行数,但是不利于代码的可读性和维护性。建议还是将它们分别写在不同的行上,如下所示:
```
info = soup.select(f"#main > div:nth-child({i}) > ul")
info1 = soup.select(f"#main > div:nth-child({i}) > h2")
```
这样可以使代码更加清晰易读,并且方便后期修改和维护。
将下列代码合并一下,使其看起来简洁些import requests from bs4 import BeautifulSoup headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36 Edg/114.0.1823.41'} url='https://www.ibiquges.com/xiaoshuodaquan/' strhtml=requests.get(url,headers=headers) soup=BeautifulSoup(strhtml.text,'lxml') info=soup.select('#main > div:nth-child(1) > ul') for item in info: print(item.get_text()) count = len(info[0].find_all('li')) print(count) info1=soup.select('#main > div:nth-child(3) > ul') for item in info1: print(item.get_text()) count1 = len(info1[0].find_all('li')) print(count1) info2=soup.select('#main > div:nth-child(5) > ul') for item in info2: print(item.get_text()) count2 = len(info2[0].find_all('li')) print(count2) info3=soup.select('#main > div:nth-child(7) > ul') for item in info3: print(item.get_text()) count3 = len(info3[0].find_all('li')) print(count3) info4=soup.select('#main > div:nth-child(9) > ul') for item in info4: print(item.get_text()) count4 = len(info4[0].find_all('li')) print(count4) info5=soup.select('#main > div:nth-child(11) > ul') for item in info5: print(item.get_text()) count5 = len(info5[0].find_all('li')) print(count5) info6=soup.select('#main > div:nth-child(13) > ul') for item in info6: print(item.get_text()) count6 = len(info6[0].find_all('li')) print(count6)
import requests
from bs4 import BeautifulSoup
headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36 Edg/114.0.1823.41'}
url='https://www.ibiquges.com/xiaoshuodaquan/'
strhtml=requests.get(url,headers=headers)
soup=BeautifulSoup(strhtml.text,'lxml')
info_list = []
count_list = []
for i in range(1, 14, 2):
info = soup.select(f'#main > div:nth-child({i}) > ul')
for item in info:
print(item.get_text())
count = len(info[0].find_all('li'))
count_list.append(count)
info_list.append(info)
print(count_list)
阅读全文