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

WBOY
Release: 2016-06-06 20:13:07
Original
1502 people have browsed it

<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>
Copy after login
Copy after login

以上是我的代码,使用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>
Copy after login
Copy after login

以上是我的代码,使用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)这不是无中生有吗?

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template