아래 포럼과 비슷한 게시자를 위해이 포럼을 수색했기 때문에 중복 된 질문이 없기를 바랍니다.Python의 html 태그에서 문자열 추출하기
기본적으로 아래에 표시된 URL에서 각 우주선의 호출 부호를 긁어서 목록에 추가하는 python 스크립트를 만들었습니다. 즉, 목록을 반복하고 각 요소를 표시 할 때마다 각 호출 부호 사이에 '['및 ']'가있는 것처럼 보입니다. 내가 아래에있는 내 스크립트의 출력을 표시했습니다
출력 당신이 볼 수 있듯이
*********************** Contents of 'listOfCallSigns' List ***********************
0 ['311062900']
1 ['235056239']
2 ['305500000']
3 ['311063300']
4 ['236111791']
5 ['245639000']
6 ['235077805']
7 ['235011590']
를, 각 호출 부호의 대괄호를 보여줍니다. 이것이 BeautifulSoup 라이브러리 내의 인코딩 문제에 대한 것일 수 있다고 생각합니다.
이상적으로는 출력에 대괄호가없고 은 호출 부호 만 문자열로 사용하기를 원합니다.
*********************** Contents of 'listOfCallSigns' List ***********************
0 311062900
1 235056239
2 305500000
3 311063300
4 236111791
5 245639000
6 235077805
7 235011590
내가 현재 사용하고이 스크립트는 다음과 같습니다
내 스크립트
# Importing the modules needed to run the script
from bs4 import BeautifulSoup
import urllib2
import re
import requests
import pprint
# Declaring the url for the port of hull
url = "http://www.fleetmon.com/en/ports/Port_of_Hull_5898"
# Opening and reading the contents of the URL using the module 'urlib2'
# Scanning the entire webpage, finding a <table> tag with the id 'vessels_in_port_table' and finding all <tr> tags
portOfHull = urllib2.urlopen(url).read()
soup = BeautifulSoup(portOfHull)
table = soup.find("table", {'id': 'vessels_in_port_table'}).find_all("tr")
# Declaring a list to hold the call signs of each ship in the table
listOfCallSigns = []
# For each row in the table, using a regular expression to extract the first 9 numbers from each ship call-sign
# Adding each extracted call-sign to the 'listOfCallSigns' list
for i, row in enumerate(table):
if i:
listOfCallSigns.append(re.findall(r"\d{9}", str(row.find_all('td')[4])))
print "\n\n*********************** Contents of 'listOfCallSigns' List ***********************\n"
# Printing each element of the 'listOfCallSigns' list
for i, row in enumerate(listOfCallSigns):
print i, row
사람이 각각의 호출 부호 그냥 디스플레이를 둘러싼 대괄호를 제거하는 방법을 알고 있나요 그 끈?
미리 감사드립니다. :)에
브릴리언트! 이것은 효과가있다! 저는 매우 흥미가 있습니다. 행 [0]을 삽입하면 대괄호가 제거되는 이유를 설명해 주시겠습니까? 이제 각 목록 요소를 문자열로 반환합니까? – user3560844
목록에서 문자열을 가져 오는 방법에 대한 세부 정보를 추가하기 위해 답을 편집했습니다. – ncocacola
굉장해! 고마워요! – user3560844