Python 漂亮的汤:刮表数据
我希望从下面的url中提取表数据。具体来说,我想提取第一列中的数据。当我运行下面的代码时,第一列中的数据会重复多次。如何使值在表中仅显示一次Python 漂亮的汤:刮表数据,python,python-3.x,web-scraping,beautifulsoup,python-requests,Python,Python 3.x,Web Scraping,Beautifulsoup,Python Requests,我希望从下面的url中提取表数据。具体来说,我想提取第一列中的数据。当我运行下面的代码时,第一列中的数据会重复多次。如何使值在表中仅显示一次 from urllib.request import urlopen from bs4 import BeautifulSoup html = urlopen('http://www.pythonscraping.com/pages/page3.html').read() soup = BeautifulSoup(html, 'lxml') table =
from urllib.request import urlopen
from bs4 import BeautifulSoup
html = urlopen('http://www.pythonscraping.com/pages/page3.html').read()
soup = BeautifulSoup(html, 'lxml')
table = soup.find('table',{'id':'giftList'})
rows = table.find_all('tr')
for row in rows:
data = row.find_all('td')
for cell in data:
print(data[0].text)
试试这个:
from urllib.request import urlopen
from bs4 import BeautifulSoup
html = urlopen('http://www.pythonscraping.com/pages/page3.html').read()
soup = BeautifulSoup(html, 'lxml')
table = soup.find('table',{'id':'giftList'})
rows = table.find_all('tr')
for row in rows:
data = row.find_all('td')
if (len(data) > 0):
cell = data[0]
print(cell.text)
将
请求
模块与选择器
结合使用,您还可以尝试以下操作:
import requests
from bs4 import BeautifulSoup
link = 'http://www.pythonscraping.com/pages/page3.html'
soup = BeautifulSoup(requests.get(link).text, 'lxml')
for table in soup.select('table#giftList tr')[1:]:
cell = table.select_one('td').get_text(strip=True)
print(cell)
输出:
Vegetable Basket
Russian Nesting Dolls
Fish Painting
Dead Parrot
Mystery Box
如何仅从第一列提取数据?@Zach要打印每行的第一列吗?@ozy。对我只需要数据中的第一列。@Zach我已经编辑了代码。这能满足你的需要吗?如果答案是正确的,请接受。太好了!正是我需要的。