【问题标题】:How to print scraped output of 2 p tags in 1 line with a space如何在 1 行中用空格打印 2 p 个标签的抓取输出
【发布时间】:2021-06-16 19:49:37
【问题描述】:

我已经添加了 HTML 和我编写的爬虫。我希望将p(2 个p 标签)标签内容打印在 1 行中。就像珍贵的 Achiuwa。然后在下一行,我要打印另外2个p元素内容。

<td class="primary text RosterRow_primaryCol__19xPQ">
 <a class="flex items-center t6 Anchor_complexLink__2NtkO" href="/player/1630173/precious-achiuwa/">
  <div class="w-8 h-8 mr-2">
   <img alt="Precious Achiuwa Headshot" class="PlayerImage_image__1smob PlayerImage_round__281uY" loading="lazy" src="https://cdn.nba.com/headshots/nba/latest/260x190/1630173.png"/>
  </div>
  <div class="flex flex-col lg:flex-row">
   <p class="t6 mr-1">
    Precious
   </p>
   <p class="t6">
    Achiuwa
   </p>
  </div>
 </a>
</td>
from selenium import webdriver
from bs4 import BeautifulSoup as bs

driver = webdriver.Chrome(
    executable_path=r'C:\Users\silvi\projects\selenium_basics\chromedriver.exe')
url = 'https://www.nba.com/players'
driver.get(url)

soup = bs(driver.page_source, 'lxml')

info_box = soup.find('table', class_='players-list')

names = info_box.find_all('p')
for name in names:
    r = name.get_text(' ', strip=True)
    print(r)

driver.quit()

【问题讨论】:

    标签: python-3.x web-scraping beautifulsoup


    【解决方案1】:

    要从页面打印所有玩家名称,您可以使用以下示例:

    import requests
    from bs4 import BeautifulSoup
    
    url = "https://www.nba.com/players"
    soup = BeautifulSoup(requests.get(url).content, "html.parser")
    
    for tag in soup.select("tbody .primary"):
        print(tag.get_text(strip=True, separator=" "))
    

    打印:

    Precious Achiuwa
    Jaylen Adams
    Steven Adams
    Bam Adebayo
    LaMarcus Aldridge
    Ty-Shon Alexander
    Nickeil Alexander-Walker
    Grayson Allen
    Jarrett Allen
    Al-Farouq Aminu
    Kyle Anderson
    Giannis Antetokounmpo
    Kostas Antetokounmpo
    Thanasis Antetokounmpo
    Carmelo Anthony
    Cole Anthony
    OG Anunoby
    Ryan Arcidiacono
    Trevor Ariza
    D.J. Augustin
    Deni Avdija
    Deandre Ayton
    Udoka Azubuike
    Dwayne Bacon
    Marvin Bagley III
    LaMelo Ball
    Lonzo Ball
    Mo Bamba
    Desmond Bane
    Harrison Barnes
    RJ Barrett
    Will Barton
    Keita Bates-Diop
    Nicolas Batum
    Aron Baynes
    Kent Bazemore
    Darius Bazley
    Bradley Beal
    Malik Beasley
    Jordan Bell
    DeAndre' Bembry
    Davis Bertans
    Patrick Beverley
    Saddiq Bey
    Tyler Bey
    Khem Birch
    Goga Bitadze
    Bismack Biyombo
    Nemanja Bjelica
    Eric Bledsoe
    

    【讨论】:

    • 谢谢。你能解释一下分隔符=“”的用法吗?我对 python 和网络抓取有点陌生。如果你向我解释一下会很有帮助。
    • @SilviaIslamEera separator=" " 参数将在标签中的每个文本之间添加一个空格 " "。所以&lt;div&gt;TEXT1&lt;/div&gt;&lt;div&gt;TEXT2&lt;/div&gt; 会变成"TEXT1 TEXT2"。没有这个参数,它会变成"TEXT1TEXT2"
    猜你喜欢
    • 2021-10-25
    • 2018-01-09
    • 1970-01-01
    • 1970-01-01
    • 2015-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多