2017-07-16 61 views
1

我是Python新手。以下是Python中的一些編碼行,用於打印出http://www.nytimes.com/上的所有文章標題。打印文章標題

import requests 
from bs4 import BeautifulSoup 
base_url = 'http://www.nytimes.com' 
r = requests.get(base_url) 
soup = BeautifulSoup(r.text) 
    for story_heading in soup.find_all(class_="story-heading"):   
    if story_heading.a: 
      print(story_heading.a.text.replace("\n", " ").strip()) 
     else: 
      print(story_heading.contents[0].strip()) 

.a.text是什麼意思?

非常感謝。

回答

2

首先,讓我們看看談不上什麼打印一體story_heading給我們:

>>> story_heading 
<h2 class="story-heading"><a href="https://www.nytimes.com/real-estate/mortgage-calculator">Mortgage Calculator</a></h2> 

要提取a標籤,我們訪問它使用story_heading.a

>>> story_heading.a 
<a href="https://www.nytimes.com/real-estate/mortgage-calculator">Mortgage Calculator</a> 

爲了只得到文本裏面的標籤本身,而不是它的屬性,我們使用.text

>>> story_heading.a.text 
'Mortgage Calculator' 
+1

非常感謝你們中的文本。還有一個問題:點是什麼。意思? –

+1

在Python和其他面向對象編程(OOP)語言中,使用點來調用某個類的方法。例如,內建的類'str'(string)有一個名爲'upper'的方法,它將所有的字符轉換爲大寫,來調用它,我們這樣做:'a =「這是一個字符串」'然後'a .upper()',或者簡單的''這是一個字符串「.upper()'。看起來你對Python真的很陌生,[documentation](https://docs.python.org/3/library/string.html)有關於它的內置類的語法和方法的非常好的文本,如果你想進一步討論這個話題。 –

+1

只是一個修正,最終沒有使用'()'的寫法實際上並不是調用方法,而是隻引用與方法相關的對象。 –

0

這裏, 。一個給你的第一錨標記 的.text給你的標籤