最近的一个课程项目需要随机生成名字,网上已有的解决方案是将姓,名放在两个数组里,然后随机组合,但是个人感觉不是很优雅。
找到一个这样的网站。传送门。
这不正是我想要的吗。。。
还等什么,直接上代码吧。
import requests
from bs4 import BeautifulSoup as bs
import random
def get_familyName_links():
base_url = "https://www.yw11.com/"
url = "https://www.yw11.com/qiming.php"
r = requests.get(url)
r.encoding = r.apparent_encoding
soup = bs(r.text,"html.parser")
familyNames = soup.find_all("ul",{"class":"e3"})[0]
familyName_links = {}
for familyName in familyNames:
familyName_links[familyName.a.get_text()] = base_url+familyName.a["href"]
return familyName_links
def get_names(url):
r = requests.get(url)
r.encoding = r.apparent_encoding #避免中文乱码
soup = bs(r.text,"html.parser")
selector = soup.select("body > div.listmain > div.listleft > div.listbox > div.listbox1_text")[0]
names = []
for i in selector.ul.find_all("li"):
names.append(i.get_text().strip())
return names
def get_all_names(num_of_familyName = 3,num_of_name_per_familyName = 10):
all_names = []
familyName_links = get_familyName_links()
familyNameCounter = 0
for familyName,url in familyName_links.items():
familyNameCounter += 1
names = get_names(url)
for i in range(num_of_name_per_familyName):
all_names.append(names[i])
if familyNameCounter == num_of_familyName:
break;
return all_names
def write_names_to_file(names):
random.shuffle(names)
with open("names.txt","w") as f:
for name in names:
f.write(name+"\n")
if __name__ == '__main__':
write_names_to_file(get_all_names())
参考网站:
表情来源