的步骤如下:
import requests
from bs4 import BeautifulSoup
url = "https://leetcode.com/problems/{problem_slug}/"
response = requests.get(url)
html_content = response.text
其中,{problem_slug}
是具体问题的slug,例如"two-sum"。
soup = BeautifulSoup(html_content, 'html.parser')
title = soup.find("h4").text.strip()
description = soup.find("div", class_="content__u3I1 question-content__JfgR").text.strip()
这里使用了BeautifulSoup的find
方法来查找特定的HTML元素,并使用.text
属性获取元素的文本内容。注意,具体的HTML元素和类名可能会因网站结构变化而有所不同,需要根据实际情况进行调整。
tags = [tag.text for tag in soup.find_all("a", class_="topic-tag__1jni")]
综上所述,使用requests和BeautifulSoup解析leetcode问题内容的完整代码如下:
import requests
from bs4 import BeautifulSoup
def parse_leetcode_problem(problem_slug):
url = "https://leetcode.com/problems/{problem_slug}/"
response = requests.get(url)
html_content = response.text
soup = BeautifulSoup(html_content, 'html.parser')
title = soup.find("h4").text.strip()
description = soup.find("div", class_="content__u3I1 question-content__JfgR").text.strip()
tags = [tag.text for tag in soup.find_all("a", class_="topic-tag__1jni")]
return {
"title": title,
"description": description,
"tags": tags
}
这个函数会返回一个包含问题标题、描述和标签的字典。你可以根据需要进一步扩展该函数,提取更多信息或进行其他操作。
注意:以上代码仅用于解析leetcode问题内容的示例,实际应用中可能需要处理更复杂的HTML结构和异常情况。
领取专属 10元无门槛券
手把手带您无忧上云