Home  >  Article  >  Backend Development  >  用bs4爬取标签内的text的问题

用bs4爬取标签内的text的问题

WBOY
WBOYOriginal
2016-06-06 20:13:071499browse

<code class="python">def get_coursename(info):
  info = get_content(url)
  soup = BeautifulSoup(info)
  
  all_coursename = soup.find_all('h2', class_="color-primary-text headline-1-text flex-1")
  
  #print all_coursename
  
  f = open("course_coursename.txt","w")
  for coursename in all_coursename:
      detail = soup.h2.get_text()
      
      print detail
      f.write(detail + '\n' )
      f.close
  return all_coursename</code>

以上是我的代码,使用soup.find_all()函数后在coursera得到64个标签段,但是使用递归对象和写入文件后,controlb后得到了64个第一个课程的名字,如下,求大神解答

Buddhism and Modern Psychology
Buddhism and Modern Psychology
.
.
.
.

回复内容:

<code class="python">def get_coursename(info):
  info = get_content(url)
  soup = BeautifulSoup(info)
  
  all_coursename = soup.find_all('h2', class_="color-primary-text headline-1-text flex-1")
  
  #print all_coursename
  
  f = open("course_coursename.txt","w")
  for coursename in all_coursename:
      detail = soup.h2.get_text()
      
      print detail
      f.write(detail + '\n' )
      f.close
  return all_coursename</code>

以上是我的代码,使用soup.find_all()函数后在coursera得到64个标签段,但是使用递归对象和写入文件后,controlb后得到了64个第一个课程的名字,如下,求大神解答

Buddhism and Modern Psychology
Buddhism and Modern Psychology
.
.
.
.

你的for循环里应该使用循环变量coursename而不是soup

代码不全啊,我发现几个小问题。你的get_coursename()的参数 info 是不是多余了?另外你在get_coursename()里面直接调用get_content(url)这不是无中生有吗?

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn