from requests import get
value = '벨류값'
URL = '내사이트'
원본
print get('{}/경로/value={}'.format(URL, value).text.split('<!DOCTYPE html>')[0]
수정
print (get('{}/경로/value={}'.format(URL, value).text.split('<!DOCTYPE html>')[0])
파이썬 코드가 현재 이런식으로 되어있는데
막상 실행하면 코드는 적용되나, text split으로 보여주질 않습니다.
혹시 제가 모르는 부분이나 잘못된 부분이 있다면 말씀부탁드립니다
* 수정한 이유는 파이썬최신에서 원본코드가 실행되지 않아 최신코드형태로 수정했습니다.
답변 4개 / 댓글 1개
오래된 질문이지만, 같은 코드로 검색하실 분을 위해 두 가지를 구분해 보완합니다. 질문의 수정 코드 그대로라면 format() 뒤에 get()을 닫는 괄호가 하나 빠져 있습니다. 요청과 문자열 처리를 분리하면 확인하기 쉽습니다.
Copy
또한 split(...)[0]은 HTML 본문이 아니라 해당 문자열 '앞'의 내용입니다. 응답이 <!DOCTYPE html>로 시작하면 결과는 정상적으로 빈 문자열 ''이 됩니다. 반대로 구분 문자열이 없거나 대소문자가 다르면 전체 문자열이 그대로 나옵니다. 따라서 빈 출력만으로 요청 실패라고 판단할 수는 없습니다.
HTML 전체가 필요하면 print(text), 특정 태그의 내용이 필요하면 HTML 파서로 해당 요소를 선택하시면 됩니다. 위 코드는 질문의 URL 구조를 그대로 둔 예시이며 실제 사이트에 접속해 검증한 것은 아닙니다.
참고: https://docs.python.org/3/library/stdtypes.html#str.split
https://requests.readthedocs.io/en/latest/user/quickstart/
from requests import get
response = get('{}/경로/value={}'.format(URL, value), timeout=10)
response.raise_for_status()
text = response.text
print(repr(text[:100])) # 응답 앞부분 확인(로컬에서만)
print(repr(text.split('<!DOCTYPE html>', 1)[0]))
※ 문자열 Data를 처리하지 못함일 것입니다 !
>>> 경로나 값이 문제를 일으킬 수 있음
>>> 약간 다른 구성입니다.
Copy
from requests import get, RequestException
value = 'values'
URL = 'My_site'
try:
print(f"Requesting URL: {URL}/경로/value={value}")
response = get(f"{URL}/경로/value={value}")
if response.status_code == 200:
if '<!DOCTYPE html>' in response.text:
print(response.text.split('<!DOCTYPE html>')[0])
else:
print("Expected HTML format not found in response.")
else:
print(f"Request failed with status code: {response.status_code}")
print("Check if the path or URL is correct.")
except RequestException as e:
print("A network error occurred. Please check the network connection or the server status.")
print(f"Error details: {e}")
=== 참고만 하세요 ~
> 실패 이유가 경로 문제인지,
값 문제인지, 혹은 응답 형식의 문제인지 명확히 알 수 있을 것입니다.
. .
※ 실 사용으로, <!DOCTYPE html>태그 이전의 텍스트를 가져오는데 사용할 만한 소스.
Copy
from requests import get, RequestException
value = 'values'
URL = 'My_site'
def fetch_content(url, path, value):
full_url = f"{url}/{path}/value={value}"
try:
response = get(full_url, timeout=5)
if response.status_code == 200:
content = response.text
split_content = content.split('<!DOCTYPE html>', 1)[0]
if split_content:
return split_content
else:
return "No content found before <!DOCTYPE html>."
else:
return f"Request failed with status code: {response.status_code}."
except RequestException as e:
return f"Network error: {e}"
result = fetch_content(URL, '경로', value)
print(result)
답변을 작성하려면 로그인이 필요합니다.
프린트를 원하는 구문을 모두 묶어줘야하며
print (get('{}/경로/value={}'.format(URL, value).text.split('<!DOCTYPE html>')[0])
수정된 구문이 문제가 없어 보이는데 경로지정 혹은 벨류값 문제로 보여집니다.